Laravel 10 Multiple Image Upload Preview Example

In this tutorial, we will show you how to upload multiple images with preview and delete option using jQuery Ajax in Laravel 10.

We will use the jQuery File Upload plugin to implement this functionality. This plugin is very easy to use and also provides a lot of options to customize the file upload.

Step 1: Install Laravel 10

First, we need to install the latest version of Laravel 10. We can install it using the composer command.

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

Step 2: Create Migration and Model

Now, we need to create a migration and model for the images table. We can generate it using the following command.

php artisan make:migration create_images_table

This command will create a migration file in the database/migrations directory.

Step 3: Setup Database

Now, we need to setup the database. We can do this by editing the .env file and setting the database credentials.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

Step 4: Create Image Model

Now, we need to create an Image model. We can generate it using the following command.

php artisan make:model Image

This command will create an Image model in the app directory.

Step 5: Add Routes

Now, we need to add routes for the image upload and delete functionality. We can do this by adding the following routes in the routes/web.php file.

Route::post(‘/upload-images’, ‘ImageController@uploadImages’);
Route::delete(‘/delete-image/{id}’, ‘ImageController@deleteImage’);

Step 6: Create Image Controller

Now, we need to create an ImageController. We can generate it using the following command.

php artisan make:controller ImageController

This command will create an ImageController in the app/Http/Controllers directory.

Step 7: Add Code in Image Controller

Now, we need to add the code for the image upload and delete functionality in the ImageController. We can do this by adding the following code in the ImageController.

file(‘images’);
foreach($images as $image)
{
$imageName = $image->getClientOriginalName();
$image->move(public_path(‘images’), $imageName);
$image = new Image;
$image->name = $imageName;
$image->save();
}
return response()->json([‘success’ => ‘Images Uploaded Successfully’]);
}

public function deleteImage($id)
{
$image = Image::find($id);
$image->delete();
return response()->json([‘success’ => ‘Image Deleted Successfully’]);
}
}

Step 8: Create View File

Now, we need to create a view file for the image upload and delete functionality. We can do this by creating a file named upload.blade.php in the resources/views directory.

@extends(‘layouts.app’)

@section(‘content’)

Upload Multiple Images with Preview and Delete Option using jQuery Ajax in Laravel 10
@csrf

@if(count($images) > 0)
@foreach($images as $image)


@endsection

Step 9: Add Code in Controller

Now, we need to add the code in the controller to get the images from the database. We can do this by adding the following code in the ImageController.

public function index()
{
$images = Image::all();
return view(‘upload’, compact(‘images’));
}

Step 10: Run Development Server

Now, we need to start the development server. We can do this by running the following command.

php artisan serve

Now, we can access the application at http://localhost:8000.

If you want to implement functionality that allows users to preview multiple images before uploading them to the database and directories in your Laravel 10 web application, then this tutorial is for you. In this tutorial, you will learn how to show a preview of multiple images before the upload process in Laravel 10 application using jquery.

Laravel 10 Multiple Image Upload Preview Example

By using the following steps, you can upload multiple image and show preview in laravel 10 apps using jquery:

  • Step 1 – Setup New Laravel 10 Application
  • Step 2 – Setup Database with Laravel App
  • Step 3 – Create Model & Migration
  • Step 4 – Add 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 – Setup New Laravel 10 Application

Firstly, open your terminal and execute the following command into it to download or install Laravel 10 new setup on your system:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install Laravel 10 latest application using the following command:

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

Step 2 – Setup Database with Laravel App

In this step, Add your database details with Laravel app. So, visit to Laravel app root directory and find .env file. Then set up database details as follows:

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 – Create Model & Migration

In this step, execute the following command on terminal or command prompt to create photo migration and model file:

php artisan make:model Photo -m

The above command will create two files into your Laravel 10 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 – Add Routes

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

use App\Http\Controllers\UploadImagesController;

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, Execute the php artisan command on command line or terminal to create a controller:

php artisan make:controller UploadImagesController

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

So open the UploadImagesController.php file and add the following code to 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 this, Go to 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 text editor and update the following code into it:

<!DOCTYPE html>
<html>
<head>
<title>Laravel 10 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 10 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 browser:

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

Recommended Laravel Posts

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?