Laravel 7/6 – Multiple Image Upload with Preview

Laravel 7/6 – Multiple Image Upload with Preview

Multiple image upload in laravel 7/6 with preview and validation. Here, we will show you how to upload multiple images with preview and validation in laravel and store multiple image file into a database and folder.

If you are developing multiple image upload app in laravel. At that time, want to show preview of multiple image before uploading in laravel and save into database and folder in laravel.

So this multiple image upload with preview in laravel 7/6 tutorial will guide you step by step on how to upload multiple images with preview in laravel. As well as, how to validate multiple images before uploading & storing using laravel validation rules.

Multiple Image Upload in Laravel 7/6 with Preview

Just follow below following steps and implement multiple image upload with preview and validation app in laravel:

  1. Install Laravel App
  2. Add Database Details in Multiple Image Upload App
  3. Generate Image Migration & Model
  4. Add Multiple Image Upload Route
  5. Create Multiple Image Controller
  6. Create Blade View
  7. Run Development Server

Step 1: Install Laravel App

First of all, you need to download laravel fresh setup to build multiple image upload in laravel with preview app. So open your terminal and run the following command and download fresh new laravel setup:

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

Step 2: Add Database Details in Multiple Image Upload App

After successfully installed multiple image upload with preview in laravel app. Now, Navigate installed this app root directory and open .env file. Then add database details into .env file:

 DB_CONNECTION=mysql 
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name here
DB_USERNAME=here database username here
DB_PASSWORD=here database password here

Step 3: Generate Image Migration & Model

In this step, create a table name and migration file for storing images. So run the following command:

php artisan make:model Image -m

This command will create one model name Image and also create one migration file for Image table. After successfully run the command go to database/migrations file and put the below here :

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateImagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->increments('id');
            $table->increments('image');
            $table->timestamps();
        });
    }

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

Next, migrate the table using the below command :

php artisan migrate

Step 4: Add Multiple Image Upload Route

In this step, you need to add multiple image upload with preivew routes in the web.php file. Go to /routes/web.php file and create two routes so update your routes in web.php file:

 Route::get('multiple-image', 'ImageController@index');
 Route::post('multiple-save', 'ImageController@save');

Step 5: Create Multiple Image Upload Controller

In this step, you need to create a controller name ImageController. Use the below command and create Controller :

php artisan make:controller ImageController

After successfully create controller go to app/controllers/ImageController.php and update the below code :

The first method is index() and it will show you image upload form.

The second method is save() and it will store your images into database and folder in laravel application.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator,Redirect,Response,File;
use App\Image;

class ImageController extends Controller
{

    public function index()
    {
        return view('image');
    }

    public function save(Request $request)
    {

        request()->validate([

            'image' => 'required',
            'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'

        ]);

        if ($image = $request->file('image')) {
            foreach ($image as $files) {
            $destinationPath = 'public/image/'; // upload path
            $profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
            $files->move($destinationPath, $profileImage);
            $insert[]['image'] = "$profileImage";
            }
        }
      
        $check = Image::insert($insert);

        return Redirect::to("image")->withSuccess('Great! Image has been successfully uploaded.');

    }
}

Step 6: Create Blade view

In this step, you need to create a blade view file. Go to app/resources/views and create one file name image.blade.php:

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<link rel="stylesheet" href="{{ url('public/cssjs/bootstrap.min.css') }}" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<style>
.thumb{
    margin: 10px 5px 0 0;
    width: 300px;
} 
</style>
<body>
<article class="bg-secondary mb-3">  
<div class="card-body text-center">
<h4 class="text-white">Laravel Multiple Image Upload Tutorial With Live Preview</h4>
</div>
</article>
<div class="container">  
    @if ($message = Session::get('success'))

    <div class="alert alert-success alert-block">

        <button type="button" class="close" data-dismiss="alert">×</button>

            <strong>{{ $message }}</strong>

    </div>
    <br>
    @endif
<form id="file-upload-form" class="uploader" action="{{url('save')}}" method="post" accept-charset="utf-8" enctype="multipart/form-data">
@csrf
<input type="file" id="file-input" multiple />
<span class="text-danger">{{ $errors->first('image') }}</span>
<div id="thumb-output"></div>
<br>
<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>
</body>

</html>

Add script code in image.blade.php file:

Now, you need to add the following script code into your image.blade.php file:

<script>

$(document).ready(function(){
 $('#file-input').on('change', function(){ //on file input change
    if (window.File && window.FileReader && window.FileList && window.Blob) //check File API supported browser
    {
        
        var data = $(this)[0].files; //this file data
        
        $.each(data, function(index, file){ //loop though each file
            if(/(\.|\/)(gif|jpe?g|png)$/i.test(file.type)){ //check supported file type
                var fRead = new FileReader(); //new filereader
                fRead.onload = (function(file){ //trigger function on successful read
                return function(e) {
                    var img = $('<img/>').addClass('thumb').attr('src', e.target.result); //create image element 
                    $('#thumb-output').append(img); //append image to output element
                };
                })(file);
                fRead.readAsDataURL(file); //URL representing the file's data.
            }
        });
        
    }else{
        alert("Your browser doesn't support File API!"); //if File API is absent
    }
 });
});

</script>

Step 7: Run Development Server

Finally, you need to run the development server. So run the php artisan serve command on the terminal to start your server :

 php artisan serve
If you want to run the project diffrent port so use this below command
php artisan serve --port=8080

Now you are ready to run our example so run bellow command to quick run.

 http://localhost:8000/multiple-image

Conclusion

In this laravel multiple image upload with preview example tutorial, You have learned how to upload multiple images with preview in laravel apps. as well as upload multiple image in database and folder. Our examples run quickly.

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorAdmin

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 *