Multiple Images Upload in Laravel with Validation

vinoy · · 2152 Views
Multiple Images Upload in Laravel with Validation

Many developers face difficulties in adding image upload feature in the application. Specifically, developers are uncertain about how to upload and validate images. In this post, you will learn how to implement Laravel multiple image upload functionality with validations.

Create Laravel Project

To create a Laravel app, run the following command in the terminal:

composer create-project laravel/laravel --prefer-dist laravel-app
cd laravel-app

Database Configuration

Create database and define your database configuration in .env file.

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=

Create Image Model and Migrations

To create Image model and images table migration use following command:

php artisan make:model Image -m

Now go to the database/migration directory and open the migration file for the images table. In this migration, add column image_path.

<?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('image_path')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('images');
    }
}

Next, run the migration to create tables in the database.

php artisan migrate

Create Routes in Laravel

Go to routes/web.php and create two routes. One route to show image upload form, and the second route is to upload the image.

// Create image upload form
Route::get('/images/upload', 'ImageUploadController@show');

// Store image
Route::post('/images/upload', 'ImageUploadController@store')->name('images.store');

Create Image Uploading Controller

Run the following command to create ImageUploadController:

php make:controller ImageUploadController

Next, in the Go to app/Http/Controllers/ImageUploadController.php file, we need to create a show() method to display image upload form and store() method to upload images as shown in the following code snippet:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Image;

class ImageUploadController extends Controller
{
  public function show()
  {
    return view('images.show');
  }

  public function store(Request $request)
  {
        $request->validate([
        	'file' => 'required|image|max:2048'
        ]);

        $imageModel = new Image;

        if($request->file()) {
            $imagePath = $request->file('file')->store('uploads');
            
            $imageModel->image_path = '/uploads/' . $imagePath;
            $imageModel->save();

            return back()
	    ->with('success','Image has been uploaded.')
	    ->with('file', $imagePath);
        }
   }
}

Create Blade Template for image upload form

Create resources\views\images\show.blade.php file and add the following code.

<!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>

Finally, we have completed the Laravel Image upload feature. Its time to run this  in browser. So, in your terminal run following command:

php artisan serve

Now test this URL path (http://127.0.0.1:8000//images/upload) in your browser.

0

Please login or create new account to add your comment.

0 comments
You may also like:

Part #3: Rule objects based custom validation in Laravel

Laravel comes with multiple ways to add custom validation rules to validate form request inputs. I have already explained some of the ways in the following article links:
Harish Kumar

Part #2: How to use Laravel's Validator::extend method for custom validation

Validation is important in any application as it validates a form before performing actions on it. It allows the user to know their input is accurate and confident about the operation (...)
Harish Kumar

Part #1: Closure-based Custom Laravel Validation

While I was working with Laravel, validation using closure came to my mind, and I know it will be helpful to you. This tutorial assists you with all what is the difference between (...)
Harish Kumar

How to use the enumerations(Enums) of PHP 8.1 in Laravel?

The release of PHP 8.1 brings native enumerations to PHP. There is no more requirement for custom solutions in your Laravel projects since the Laravel v8.69 release has you back. (...)
Harish Kumar

Mobile App Development Process

With businesses adopting a mobile-first approach and the growing number of mobile apps, successful mobile app development seems like a quest. But it’s the process that determines (...)
Narola Infotech

What are Laravel Macros and How to Extending Laravel’s Core Classes using Macros with example?

Laravel Macros are a great way of expanding Laravel's core macroable classes and add additional functionality needed for your application. In simple word, Laravel Macro is an (...)
Harish Kumar