Laravel 6 Multiple Image Upload Tutorial Example

How to multiple image upload in laravel 6 from scratch. Today In this tutorial, we will show you how to upload multiple image in laravel 6 application step by step simple and easy way. We will upload multiple images with validate image type in laravel app. we will also validate image with laravel validator and store the images to database and folder.

In this tutorial, We will tell you each things about multiple image upload in laravel app. Just follow few steps and upload image in folder laravel app .

Multiple Image Upload Tutorial

Contents

Install Laravel App
Setup Database
Make Route
Create Controller & Methods
Create Blade View
Make Folder
Start Development Server
Conclusion

Install Laravel App

First of we need to download laravel fresh setup. Use the below command and download fresh new laravel setup :

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

Setup Database

After successfully install laravel 6 Application, Go to your project .env file and set up database credential and move next step :

 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

Generate Migration & Model

Now we will create table name Image and it’s migration file. use the below command :

php artisan make:model Image -m

It 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->string('image', 80);
            $table->timestamps();
        });
    }

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

Next migrate the table using the below command :

php artisan migrate

Make Route

We will create two routes in web.php file. Go to app/routes/web.php file and create two below routes here :

 Route::get('multiple-image', '[email protected]');
 Route::post('multiple-save', '[email protected]');

Create Controller

We 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 put the below code :

<?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.');

    }
}

Create Blade view

In this step we need to create 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" name="image" 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>
Put the script on multiple-image.blade.php, after closing of body tag
<script>

$(document).ready(function(){
 $('#file-input').on('change', function(){ //on file input change
    if (window.File &amp;&amp; window.FileReader &amp;&amp; window.FileList &amp;&amp; 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>

Start Development Server

We need to start development server. Use the php artisan serve command and 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 we are ready to run our example so run bellow command to quick run.

 http://localhost:8000/multiple-image

Conclusion

In this tutorial , We have successfully upload multiple image in project folder . We uploaded 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.

21 Comments

  1. Javier said:

    This piece of code gives me an error, why should I replace it?
    Two incrementals are not allowed together.

    $table->increments(‘id’);
    $table->increments(‘image’);
    $table->timestamps();

    September 24, 2019
    Reply
    • w3path said:

      Thanks to pointing me here,
      Please change the $table->increments(‘image’); to $table->string(‘image’, 80);

      September 29, 2019
      Reply
  2. Javier said:

    The Image model that was generated with the artisan command looks as follows:
    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Image extends Model
    {
    //
    }
    would be missing add? :
    protected $table = 'images';

    September 24, 2019
    Reply
    • w3path said:

      No, you don’t need to add this line, Laravel convert class name to table name itself.

      September 29, 2019
      Reply
  3. sean treanor said:

    This lets you upload zip files so your logic that prevents other file types from being uploaded is not working correctly.

    October 2, 2019
    Reply
  4. sirgliofrei said:

    I went over this internet site and I think you have a lot of superb information, saved to fav (:.

    October 12, 2019
    Reply
  5. Silky said:

    On line 34 of image.blade.php, you are missing the name attribute on the image input field.

    November 10, 2019
    Reply
    • w3path said:

      Thanks to letting me know. Now it is fixed

      November 11, 2019
      Reply
  6. Jobs said:

    I appreciate you sharing this blog post.

    November 14, 2019
    Reply
  7. Miguel Angel Gonzalez Serrano said:

    Existe un error no recibe el array

    Se tiene que sustituir por:

    December 14, 2019
    Reply
  8. vitesh coderkube said:

    hello please give me code of zip file.

    March 21, 2020
    Reply
  9. Virgilio said:

    Excellent article. Keep posting such kind of information on your page.

    Im really impressed by your blog.
    Hey there, You have performed a great job. I’ll definitely digg it and for
    my part suggest to my friends. I’m confident they will be
    benefited from this web site.

    My blog post; cheap flights

    January 31, 2021
    Reply
  10. Henrietta said:

    When I originally left a comment I appear to have clicked the -Notify
    me when new comments are added- checkbox and now every
    time a comment is added I receive 4 emails with the exact same comment.
    Is there a way you are able to remove me from that service?
    Appreciate it!

    Stop by my website; cheap flights

    February 1, 2021
    Reply
  11. Zoe said:

    Right here is the right web site for anybody who wishes to understand this topic.
    You realize a whole lot its almost tough
    to argue with you (not that I really would want to…HaHa).
    You certainly put a fresh spin on a subject that’s been discussed for many
    years. Great stuff, just wonderful!

    my website … cheap flights

    February 1, 2021
    Reply
  12. Candelaria said:

    Having read this I thought it was really enlightening.

    I appreciate you taking the time and energy to put this article together.
    I once again find myself spending way too much time both reading and leaving
    comments. But so what, it was still worthwhile!

    My web-site … cheap flights (http://tinyurl.com/y4zww96v)

    February 2, 2021
    Reply
  13. Sammie said:

    I don’t know if it’s just me or if everyone else experiencing issues with
    your blog. It looks like some of the written text in your content are running off the screen. Can someone else please provide feedback and let me know if this is happening to them too?
    This might be a issue with my web browser because I’ve had this
    happen previously. Kudos

    Here is my blog :: cheap flights

    February 2, 2021
    Reply
  14. Katrice said:

    Hi there terrific blog! Does running a blog like this
    require a lot of work? I have no understanding of computer programming but I was hoping to start my own blog soon.
    Anyways, if you have any suggestions or techniques for new blog owners please share.
    I know this is off subject however I simply wanted to ask.
    Kudos!

    my blog post; cheap flights [http://tinyurl.com/]

    February 3, 2021
    Reply
  15. Helene said:

    First of all I would like to say superb blog!
    I had a quick question which I’d like to ask if
    you do not mind. I was interested to know how you center yourself and clear your head before writing.

    I’ve had a difficult time clearing my thoughts in getting my thoughts
    out. I do take pleasure in writing however it just seems like
    the first 10 to 15 minutes tend to be wasted just trying to figure out how to begin. Any suggestions
    or tips? Thanks!

    Also visit my web site – cheap flights (tinyurl.com)

    February 12, 2021
    Reply
  16. https://shiatsu-web.com said:

    This is something New !

    February 12, 2021
    Reply
  17. n95 masks said:

    Are you okay? I’m concerned about you. Please be ok!

    February 18, 2021
    Reply
  18. buy face masks said:

    WHY? 🙂

    February 22, 2021
    Reply

Leave a Reply

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