In this tutorial you will learn about the Laravel 8 Multiple Images Upload with Validation Example and its application with practical example.
In this Laravel 8 Multiple Images Upload with Validation Example Tutorial, I will show you how to upload multiple image with validation in laravel 8. In this tutorial you will learn to upload multiple image in laravel with validation and save into folder and then save it into database. In this example before saving multiple image into database we will validate image and then save it into directory. Before uploading the image we will validate the image. After successfully uploading multiple images into the folder and saving it in database we will display success message on the screen.
Laravel 8 Multiple Images Upload with Validation Example
In this step by step tutorial I’ll demonstrate example of multiple image upload with Validation in laravel 8. Please follow the step given below:
- Create Project
- Database Configuration
- Create Model and Migrations
- Create Controller
- Create Routes
- Create Blade File
Create Laravel Project
First of all we need to create a fresh laravel project, download and install Laravel 8 using the below command
1 |
composer create-project laravel/laravel --prefer-dist laravel-image-upload |
Now switch to the project directory.
1 |
cd laravel-image-upload |
Database Configuration
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=localhost DB_PORT=3306 DB_DATABASE=laravel_db DB_USERNAME=root DB_PASSWORD= |
Create Model and Migrations
Now, in this step we will create model and migration file. Please run the following command:
1 |
php artisan make:model Image -m |
Once above command is executed there will be a migration file created inside database/migrations/ directory, open migration file and update the function up() method as following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateImagesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('images', function (Blueprint $table) { $table->id(); $table->string('name')->nullable(); $table->string('image_path')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('images'); } } |
Now put the following code inside the app/Models/Image.php file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Image extends Model { use HasFactory; protected $fillable = [ 'name', 'image_path' ]; } |
Now, run the migration to create database table using following artisan command:
1 |
php artisan migrate |
Create Image Uploading Controller
Now, lets create a controller named FileUpload using command given below –
1 |
php artisan make:controller FileUpload |
Once the above command executed, it will create a controller file FileUpload.php in app/Http/Controllers/ directory. Open the FileUpload.php file and put the following code in it.
app/Http/Controllers/FileUpload.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Image; class FileUpload extends Controller { public function createForm(){ return view('image-upload'); } public function fileUpload(Request $req){ $req->validate([ 'imageFile' => 'required', 'imageFile.*' => 'mimes:jpeg,jpg,png,gif,csv,txt,pdf|max:2048' ]); if($req->hasfile('imageFile')) { foreach($req->file('imageFile') as $file) { $name = $file->getClientOriginalName(); $file->move(public_path().'/uploads/', $name); $imgData[] = $name; } $fileModal = new Image(); $fileModal->name = json_encode($imgData); $fileModal->image_path = json_encode($imgData); $fileModal->save(); return back()->with('success', 'File has successfully uploaded!'); } } } |
The createForm() function will display image upload from in the view, and the the fileUpload() method will handle uploading, storing and validation in the image uploading controller.
Create Routes in Laravel
After this, we need to define routes in “routes/web.php” file. Lets open “routes/web.php” file and add the following routes in it.
routes/web.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\FileUpload; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/image-upload', [FileUpload::class, 'createForm']); Route::post('/image-upload', [FileUpload::class, 'fileUpload'])->name('imageUpload'); |
Create Blade Template
In this step we will create blade view file for uploading multiple images. Create resources\views\image-upload.blade.php file and add the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <title>Laravel Image Upload</title> <style> .container { max-width: 500px; } dl, ol, ul { margin: 0; padding: 0; list-style: none; } .imgPreview img { padding: 8px; max-width: 100px; } </style> </head> <body> <div class="container mt-5"> <h3 class="text-center mb-5">Image Upload in Laravel</h3> <form action="{{route('imageUpload')}}" method="post" enctype="multipart/form-data"> @csrf @if ($message = Session::get('success')) <div class="alert alert-success"> <strong>{{ $message }}</strong> </div> @endif @if (count($errors) > 0) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <div class="user-image mb-3 text-center"> <div class="imgPreview"> </div> </div> <div class="custom-file"> <input type="file" name="imageFile[]" class="custom-file-input" id="images" multiple="multiple"> <label class="custom-file-label" for="images">Choose image</label> </div> <button type="submit" name="submit" class="btn btn-primary btn-block mt-4"> Upload Images </button> </form> </div> <!-- jQuery --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script> $(function() { // Multiple images preview with JavaScript var multiImgPreview = function(input, imgPreviewPlaceholder) { if (input.files) { var filesAmount = input.files.length; for (i = 0; i < filesAmount; i++) { var reader = new FileReader(); reader.onload = function(event) { $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(imgPreviewPlaceholder); } reader.readAsDataURL(input.files[i]); } } }; $('#images').on('change', function() { multiImgPreview(this, 'div.imgPreview'); }); }); </script> </body> </html> |
Start The Application
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |
Now, open the following URL in browser to see the output –
1 |
http://127.0.0.1:8000/image-upload |