Laravel 10 image upload; In this tutorial, we will learn how to upload image to MySQL database and storage directory with validation in Laravel 10 app. And also, how to validate image mime type, size, dimensions, etc on laravel controller using laravel validation rules.
- Create a new Laravel 10 project using Composer:
composer create-project laravel/laravel your-project-name --prefer-dist
- Change to the project directory:
cd your-project-name
- Create a new migration for the images table:
php artisan make:migration create_images_table
- In the new migration file, add the following code to create the images table:
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateImagesTable extends Migration { public function up() { Schema::create('images', function (Blueprint $table) { $table->id(); $table->string('filename'); $table->string('path'); $table->integer('size'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('images'); } }
- Run the migration to create the images table:
php artisan migrate
- Create a new model for the Image:
php artisan make:model Image
- In the new model file, add the following code to define the table and its fillable attributes:
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Image extends Model { use HasFactory; protected $table = 'images'; protected $fillable = [ 'filename', 'path', 'size', ]; }
- Create a new controller for the Image:
php artisan make:controller ImageController
- In the new controller file, add the following code to define the index method to display the images:
use App\Models\Image; public function index() { $images = Image::orderBy('created_at', 'desc')->get(); return view('images.index', ['images' => $images]); }
- Create a new view for the images index:
touch resources/views/images/index.blade.php
- In the new view file, add the following code to display the images:
@if (count($images) > 0) <ul> @foreach ($images as $image) <li> <img src="{{ asset($image->path) }}" alt="Uploaded image"> <div>{{ $image->filename }}</div> <div>{{ $image->size }} bytes</div> </li> @endforeach </ul> @endif
- Create a new route for the images index:
Route::get('/images', [ImageController::class, 'index'])->name('images.index');
- Create a new view for the image upload form:
touch resources/views/images/upload.blade.php
- In the new view file, add the following code to display the image upload form:
<form action="{{ route('images.upload') }}" method="POST" enctype="multipart/form-data"> @csrf <input type="file" name="image"> <button type="submit">Upload</button> </form>
- Create a new route for the image upload form:
Route::get('/images/upload', function () { return view('images.upload'); })->name('images.upload.form');
- Create a new route to handle the image upload:
Route::post('/images/upload', [ImageController::class, 'upload'])->name('images.upload');
- In your ImageController file, add the following code to define the upload method to handle the image upload:
use App\Models\Image; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; public function upload(Request $request) { $request->validate([ 'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048', ]); $image = $request->file('image'); $filename = $image->getClientOriginalName(); $path = $image->store('public/images'); $size = $image->getSize(); $image = new Image([ 'filename' => $filename, 'path' => $path, 'size' => $size, ]); $image->save(); return redirect()->route('images.index') ->with('success','Image has been uploaded successfully.'); }
- This code validates that the image is required, an image file, of the allowed mime types, and is no larger than 2MB. If the validation passes, it uploads the file to the
public/images
folder in your storage system, saves the image data to the database, and redirects back to the images index page. - Now, you need to configure the storage system in your Laravel project. Open the
.env
file and set theFILESYSTEM_DRIVER
topublic
:
FILESYSTEM_DRIVER=public
- Also, add a new
public
disk in yourconfig/filesystems.php
file:
'disks' => [ //... 'public' => [ 'driver' => 'local', 'root' => public_path('storage'), 'url' => env('APP_URL').'/storage', 'visibility' => 'public', ], ],
- Run the following command to create a symlink to the storage directory:
php artisan storage:link
- Now, you can access the images in the
public/images
folder using theasset()
helper function. - In your ImageController file, add a
use
statement for theIlluminate\Support\Facades\Storage
facade. - If you want to display the images from the storage system, you can update your
index
method in your ImageController:
use App\Models\Image; use Illuminate\Support\Facades\Storage; public function index() { $images = Image::orderBy('created_at', 'desc')->paginate(10); return view('images.index', ['images' => $images]); }
- This code retrieves all images from the database and uses the
asset()
helper function to display the images from thepublic/images
folder. - If you want to delete an image from your storage system, you can add a
delete
method to your ImageController:
use App\Models\Image; use Illuminate\Support\Facades\Storage; public function delete(Image $image) { Storage::disk('public')->delete($image->path); $image->delete(); return redirect()->route('images.index') ->with('success','Image has been deleted successfully.'); }
- This code deletes the image file from your storage system and deletes the image record from the database.
- In your view, you can add a delete button for each image:
@if (count($images) > 0) <ul> @foreach ($images as $image) <li> <img src="{{ asset($image->path) }}" alt="Uploaded image"> <div>{{ $image->filename }}</div> <div>{{ $image->size }} bytes</div> <form action="{{ route('images.delete', $image
- In the delete form, add a CSRF token and use the HTTP DELETE method:
<form action="{{ route('images.delete', $image->id) }}" method="POST"> @csrf @method('DELETE') <button type="submit">Delete</button> </form>
- Finally, add a success message to your
index
view to show when an image is deleted:
@if (session('success')) <div class="alert alert-success"> {{ session('success') }} </div> @endif
Congratulations! You have successfully implemented image upload, storage, and deletion in your Laravel 10 application.
This Article Ideas has been taken from the following websites; which are following:
Laravel 10 Image Upload Example Tutorial
Laravel 10 Image Upload Example Tutorial
Laravel 10 CRUD and Image Upload Tutorial with Laravel Breeze and Repo Example
How to Upload Image Using Laravel 10?
Laravel 10 Image Upload With Preview Example
Leave a Reply