Laravel 9 Multiple Image Upload with Preview

Multiple image upload in laravel 9 with preview; Through this tutorial, we will learn how to upload multiple images in laravel 9 app with show preview.

This multiple image upload with preview in laravel tutorial will create multiple image upload forms and write jQuery code to display multiple images preview.

Multiple Image Upload With Preview In Laravel 9

Use the following steps to upload multiple image with preview and validation in laravel 9 apps:

  • Step 1 – Install Laravel 9 Application
  • Step 2 – Configure Database with App
  • Step 3 – Build Photo Model & Migration
  • Step 4 – Create Routes
  • Step 5 – Generate Controller using Artisan Command
  • Step 6 – Create Blade View
  • Step 7 – jQuery Code To Show Multiple Image Preview
  • Step 8 – Start Development Server
  • Step 9 – Start App on Browser

Step 1 – Install Laravel 9 Application

In step 1, open your terminal and navigate to your local webserver directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel latest application using the following command:

composer create-project --prefer-dist laravel/laravel blog

Step 2 – Configure Database with App

In step 2, open your downloaded laravel 9 apps into any text editor. Then find .env file and configure database detail like the following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3 – Build Photo Model & Migration

In this step, use the below-given command to create a photo migration and model file.

First of all, navigate to the project by using the following command:

cd / blog

Then create a model and migration file by using the following command:

php artisan make:model Photo -m

The above command will create two files into your laravel multiple image upload with validation tutorial app, which is located inside the following locations:

  • blog/app/Models/Photo.php
  • blog/database/migrations/create_photos_table.php

So, find create_photos_table.php file inside blog/database/migrations/ directory. Then open this file and add the following code into function up() on this file:

    public function up()
    {
        Schema::create('photos', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('path');
            $table->timestamps();
        });
    }

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Step 4 – Create Routes

In this step, open your web.php file, so navigate inside the routes directory. Then update the following routes into the web.php file:

use App\Http\Controllers\UploadMultipleImageController;

Route::get('upload-multiple-image-preview', [UploadImagesController::class, 'index']);

Route::post('upload-multiple-image-preview', [UploadImagesController::class, 'store']);

Step 5 – Create Controller using Artisan Command

In this step, use the below-given PHP artisan command to create a controller:

php artisan make:controller UploadImagesController

The above command will create UploadImagesController.php file, which is located inside the blog/app/Http/Controllers/ directory.

So open the UploadImagesController.php file and add the following code into it:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Photo;
class UploadImagesController extends Controller
{
   public function index()
    {
        return view('images-upload-form');
    }
    public function store(Request $request)
    {

        $validateImageData = $request->validate([
	    'images' => 'required',
            'images.*' => 'mimes:jpg,png,jpeg,gif,svg'
        ]);
        if($request->hasfile('images'))
         {
            foreach($request->file('images') as $key => $file)
            {
                $path = $file->store('public/images');
                $name = $file->getClientOriginalName();
                $insert[$key]['title'] = $name;
                $insert[$key]['path'] = $path;
            }
         }
        Photo::insert($insert);

        return redirect('upload-multiple-image-preview')->with('status', 'All Images has been uploaded successfully');
    }
}

Step 6 – Create Blade Views

In step, Go to the resources/views directory. And then create a new blade view file named images-upload-form.blade.php inside this directory.

So, open this images-upload-form.blade.php file in a text editor and update the following code into it:

<!DOCTYPE html>
<html>
<head>
  <title>Laravel 9 Upload Multiple Image With Preview using jQuery - Tutsmake.com</title>

  <meta name="csrf-token" content="{{ csrf_token() }}">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

</head>
<body>

<div class="container mt-5">

  @if(session('status'))
    <div class="alert alert-success">
        {{ session('status') }}
    </div>
  @endif

  <style>
    .images-preview-div img
    {
          padding: 10px;
          max-width: 100px;
    }
  </style>

  <div class="card">

    <div class="card-header text-center font-weight-bold">
      <h2>Laravel 9 Upload Multiple Image With Preview - Tutsmake.com</h2>
    </div>

    <div class="card-body">
        <form name="images-upload-form" method="POST"  action="{{ url('upload-multiple-image-preview') }}" accept-charset="utf-8" enctype="multipart/form-data">

          @csrf

            <div class="row">

                <div class="col-md-12">
                    <div class="form-group">
                        <input type="file" name="images[]" id="images" placeholder="Choose images" multiple >
                    </div>
                    @error('images')
                        <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                    @enderror
                </div>

                <div class="col-md-12">
                    <div class="mt-1 text-center">
                        <div class="images-preview-div"> </div>
                    </div>
                </div>

                <div class="col-md-12">
                    <button type="submit" class="btn btn-primary" id="submit">Submit</button>
                </div>
            </div>
        </form>

    </div>

  </div>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script >
    $(function() {
    // Multiple images preview with JavaScript
    var previewImages = 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() {
        previewImages(this, 'div.images-preview-div');
    });
  });
</script>
</div>
</body>
</html>

Step 7 – jQuery Code To Show Multiple Image Preview

In this step, implement the jQuery code to display or show multiple images preview before upload to database and directory in laravel app:

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script >
    $(function() {
    // Multiple images preview with JavaScript
    var previewImages = 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() {
        previewImages(this, 'div.images-preview-div');
    });
  });
</script>

Step 8 – Start Development Server

In this step, run the following command on cmd to start the development server:

php artisan serve

Step 9 – Start App on Browser

In step this, run this app on browser, so open your browser and fire the following URL into a browser:

http://127.0.0.1:8000/upload-multiple-image-preview

Recommended Laravel Tutorials

Recommended:-Laravel Try Catch

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *