Laravel 11 Multiple Image Upload Preview Example

To preview multiple images before uploading in Laravel 11, you need to create an input file upload field on the HTML view and use jQuery’s FileReader() method with for() loop to iterate over the selected images from the input file field, and then set the path to the images HTML element to display the preview.

In this guide, we will show you step-by-step how to preview multiple images before uploading to Laravel 11 with folder and database.

Laravel 11 Multiple Image Upload and Preview Example

Steps for multiple image preview before upload with using jQuery and bootstrap 5 input file in laravel 11 applications:

Step 1 – Download New Laravel Application

Run the composer create-project –prefer-dist laravel/laravel blog command on cmd or terminal window to download and setup new laravel application into your system:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

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

Step 2 – Define Routes

Now create two routes in routes/web.php for preview and upload multiple images, like the following:

use App\Http\Controllers\UploadPreviewController;

Route::get('preview-images', [UploadPreviewController::class, 'previewImages']);

Route::post('uploads', [UploadPreviewController::class, 'uploadMultipleImages']);

Step 3 – Create Preview and Upload Methods in Controller

Run php artisan make:controller UploadPreviewController command on cmd on terminal window to create controller file, which is used to handle upload and preview images to laravel folder and database using methods:

php artisan make:controller UploadPreviewController

Open UploadPreviewController.php file from blog/app/Http/Controllers/ folder, and create two methods in it like the following:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class UploadPreviewController extends Controller
{
   public function previewImages()
    {
        return view('image-upload-preview');
    }
    public function uploadMultipleImages(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();
            }
         }

        return redirect('preview-images')->with('status', 'Images has been uploaded successfully');
    }
}

Step 4 – Create Form in Blade View

Navigate to the resources/views folder and create the image-upload-preview.blade.php file in it, and then create the upload and preview image forms in the image-upload-preview.blade.php file, like the following:

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

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

  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">

</head>
<body>

<div class="container mt-5">

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

  <style>
    .previews img
    {
          padding: 10px;
          max-width: 290px;
    }
  </style>

  <div class="card">

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

    <div class="card-body">
        <form name="images-upload-form" method="POST"  action="{{ url('uploads') }}" 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="previews"> </div>
                    </div>
                </div>

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

    </div>

  </div>

</div>

</body>
</html>

Now, use the jQuery FileReader() and for() loop functions to display the preview by iterating through all the images selected by the user through the form input file:

<script src="https://code.jquery.com/jquery-3.6.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.previews');
    });
  });
</script> 

Step 5 – Start Development Server

Run php artisan serve command on cmd to start the development server for testing:

php artisan serve

Open your browser with the following URL for testing this application:

http://127.0.0.1:8000/preview-images

Conclusion

We hope you have learned how to show multiple image previews before upload to database and folder in laravel 11 applications.

If you have any questions about this guide, please comment using the comment box below.

Recommended Guides

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 *