We already know that we can upload images either in a public or storage folder. In the previous tutorial, we did see how to upload images in a public folder in Laravel. Now in this tutorial, we will see how to upload images in laravel 10 application in the storage folder.
So from this laravel 10 upload image to storage folder tutorial, we will upload the image extension, image name, image size, and image path in our database and I will upload an image file to the storage folder. Hope this how to upload image to storage in Laravel tutorial will clarify your concept that how to work with a storage directory to handle files in the Laravel application.
See the preview of this tutorial how to store image in storage folder in laravel 10:
Step 1: Download Fresh Laravel
In this first step, we need a fresh Laravel 10 application for the how do I upload files to storage folder in Laravel. So download it by the below command:
composer create-project laravel/laravel example-app
Step 2: Create Model
We are going to use the Image
model. Now create an image model and update it like below:
database/migrations
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('path');
$table->string('size');
$table->string('type');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('images');
}
};
And now update the model like:
app/Models/Image.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
use HasFactory;
protected $fillable = [
'name'
'path',
'size',
'type'
];
}
Step 3: Connect database
After successfully installing the laravel app and then configuring the database setup like below to create this how to store image in storage folder in laravel 10.
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password
Now run php artisan migrate command to update the database.
php artisan migrate
Step 4: Create Route
Now in this step, we have to create a route to create laravel upload file to storage folder.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TutorialController;
Route::get('/', [TutorialController::class,'index'])->name('welcome');
Route::post('/', [TutorialController::class,'store'])->name('store');
Step 5: Create Controller
Now in this step, we have to create a TutorialController to define this method to create upload image to storage folder laravel.
php artisan make:controller TutorialController
Now update the controller like the below:
app/Http/Controllers/TutorialController.php
<?php
namespace App\Http\Controllers;
use App\Helper\ImageManager;
use App\Models\Image;
use Illuminate\Http\Request;
class TutorialController extends Controller
{
use ImageManager;
public function index()
{
return view('welcome');
}
public function store(Request $request)
{
$request->validate([
'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
]);
$path = storage_path('images/');
!is_dir($path) &&
mkdir($path, 0777, true);
if($file = $request->file('image')) {
$fileData = $this->uploads($file,$path);
Image::create([
'name' => $fileData['fileName'],
'type' => $fileData['fileType'],
'path' => $fileData['filePath'],
'size' => $fileData['fileSize']
]);
}
return redirect()
->back()
->with('success', 'Image successfully upload.');
}
}
Step 6: Create ImageManager Trait
Now in this step, we will create an ImageManager trait so that we can reuse our code. So create it like below:
app/Helper/ImageManager.php
namespace App\Helper;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
trait ImageManager {
public function uploads($file, $path)
{
if($file) {
$fileName = time() . $file->getClientOriginalName();
Storage::disk('public')->put($path . $fileName, File::get($file));
$file_name = $file->getClientOriginalName();
$file_type = $file->getClientOriginalExtension();
$filePath = $path . $fileName;
return $file = [
'fileName' => $file_name,
'fileType' => $file_type,
'filePath' => $filePath,
'fileSize' => $this->fileSize($file)
];
}
}
public function fileSize($file, $precision = 2)
{
$size = $file->getSize();
if ( $size > 0 ) {
$size = (int) $size;
$base = log($size) / log(1024);
$suffixes = array(' bytes', ' KB', ' MB', ' GB', ' TB');
return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
}
return $size;
}
}
Step 7: Create Views
In this step, we will create a form for upload image to storage folder laravel. So update the welcome file like below:
resources/views/welcome.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header" style="background: gray; color:#f1f7fa; font-weight:bold;">
Laravel 10 Upload Image To Storage Folder Preview - Laravelia
</div>
<div class="card-body">
<form class="w-px-500 p-3 p-md-3" action="{{ route('store') }}" method="post" enctype="multipart/form-data">
@csrf
<div class="row mb-3">
<label class="col-sm-3 col-form-label">Image</label>
<div class="col-sm-9">
<input type="file" class="form-control" name="image" @error('image') is-invalid @enderror id="selectImage">
</div>
@error('image')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
<img id="preview" src="#" alt="your image" class="mt-3" style="display:none;"/>
</div>
<div class="row mb-3">
<label class="col-sm-3 col-form-label"></label>
<div class="col-sm-9">
<button type="submit" class="btn btn-success btn-block">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
@push('script')
<script>
selectImage.onchange = evt => {
preview = document.getElementById('preview');
preview.style.display = 'block';
const [file] = selectImage.files
if (file) {
preview.src = URL.createObjectURL(file)
}
}
</script>
@endpush
Now we need to create a master file. So create a app.blade.php file and add it to the following path:
resources/views/layouts/app.blade.php
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Tailwindcss -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Scripts -->
@vite(['resources/sass/app.scss', 'resources/js/app.js'])
@stack('style')
</head>
<body>
<div id="app">
<nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm">
<div class="container">
<a class="navbar-brand" href="{{ url('/') }}">
Laravelia
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<!-- Left Side Of Navbar -->
<ul class="navbar-nav me-auto">
</ul>
<!-- Right Side Of Navbar -->
<ul class="navbar-nav ms-auto">
<!-- Authentication Links -->
@guest
@if (Route::has('login'))
<li class="nav-item">
<a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
</li>
@endif
@if (Route::has('register'))
<li class="nav-item">
<a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
</li>
@endif
@else
<li class="nav-item dropdown">
<a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
{{ Auth::user()->name }}
</a>
<div class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="{{ route('logout') }}"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
{{ __('Logout') }}
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
@csrf
</form>
</div>
</li>
@endguest
</ul>
</div>
</div>
</nav>
<main class="py-4" style="background: #f1f7fa;">
@yield('content')
</main>
</div>
@stack('script')
</body>
</html>
Read also: Laravel 10 Crop Image Before Upload With Cropper Js
Conclusion
I have tried my best to create this laravel upload image to storage tutorial. Now we know how to upload image in storage folder in laravel. Hope this upload image to storage folder laravel tutorial will help you to create laravel upload file to storage.