Laravel 8 Multiple Images Upload with Validation Example

Laravel 8 Multiple Images Upload with Validation Example

Steps to Implement Multiple Image Upload in Laravel 8

  1. Create a Laravel Project: Run the following command to create a new Laravel project:

    composer create-project laravel/laravel --prefer-dist laravel-image-upload cd laravel-image-upload
  2. Define Database Configuration: Set up your local database connection in the .env file:

    DB_CONNECTION=mysql DB_HOST=localhost DB_PORT=3306 DB_DATABASE=laravel_db DB_USERNAME=root DB_PASSWORD=
  3. Create Model and Migration: Create a model and migration file for the images:

    php artisan make:model Image -m

    In the migration file database/migrations/timestamp_create_images_table.php, define the schema:

    Schema::create('images', function (Blueprint $table) { $table->id(); $table->string('name')->nullable(); $table->string('image_path')->nullable(); $table->timestamps(); });

    Then, run the migration to create the table:

    php artisan migrate
  4. Create Controller: Generate a controller to handle image uploading:

    php artisan make:controller PhotosController

    In app/Http/Controllers/PhotosController.php, define methods for the form view and file upload:

    public function view(){ return view('photos'); } public function store(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!'); } }
  5. Create Routes: In routes/web.php, define routes for displaying the form and handling the image upload:

    Route::get('photos', 'App\Http\Controllers\PhotosController@view')->name('photos'); Route::post('photos/store', 'App\Http\Controllers\PhotosController@store')->name('photos/store');
  6. Create Blade Template: Create a Blade view file resources/views/photos.blade.php for the image upload form and preview:

    <form action="{{ route('photos/store') }}" method="post" enctype="multipart/form-data"> @csrf <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> <script> $(function() { 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>
  7. Start the Application: After setting up everything, start the Laravel development server:

    php artisan serve

    Visit the application at:

    http://127.0.0.1:8000/photos

This tutorial demonstrates how to upload multiple images with validation and save the paths to a MySQL database, providing a complete solution for image management in Laravel.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

2 Comments

CAN FEEDBACK
  1. Unknown
    Unknown
    Hi! please how to remove or change seleced image before uploading and how to update specific image after uploadin. Thank you for your help
  2. Anonymous
    Anonymous
    gfd
close