AppDividend
Latest Code Tutorials

Laravel Multiple Images Upload Tutorial Example From Scratch

18,503

Get real time updates directly on you device, subscribe now.

Laravel Multiple Images Upload Tutorial Example From Scratch is today’s leading topic. We will build a simple multiple images upload system using Laravel 5.5. We will use a jQuery plugin to populate image field and submit the multiple images to the server. The server checks all the inputs against defined validation, and if any of the validation fails, it will redirect to our create page with error messages.

Laravel Multiple Images Upload Tutorial

First, we download a fresh copy of Laravel project by typing the following command.

Step 1: Configure Laravel.

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

After installing the Laravel, configure the database. So go to the .env file and add the database credentials.

Then we need to create a migration file to store the images name. So go to the CMD and hit the following command.

php artisan make:migration create_forms_table

Define the schema as follows.

<?php

// create_forms_table.php

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

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

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

Next step will be to migrate this schema and make a table in the database.

php artisan migrate

Now, we need to setup controller and model file for our application. Type the following command to generate model and controller.

php artisan make:model Form

php artisan make:controller FormController

It will generate two files.

  1. Form.php
  2. FormController.php

Step 2: Define routes in the web.php file.

Go to the routes  >>  web.php file and add the following routes.

// web.php

Route::get('form','FormController@create');
Route::post('form','FormController@store');

In the FormController’s create a function, write the following code.

// FormController.php

/**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        return view('create');
    }

Now, let us make a create.blade.php file inside views folder.

<html lang="en">
<head>
  <title>Laravel Multiple File Upload Example</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
  
  <div class="container">
       
    <h3 class="jumbotron">Laravel Multiple File Upload</h3>
<form method="post" action="{{url('form')}}" enctype="multipart/form-data">
  {{csrf_field()}}

        <div class="input-group control-group increment" >
          <input type="file" name="filename[]" class="form-control">
          <div class="input-group-btn"> 
            <button class="btn btn-success" type="button"><i class="glyphicon glyphicon-plus"></i>Add</button>
          </div>
        </div>

        <button type="submit" class="btn btn-primary" style="margin-top:10px">Submit</button>

  </form>        
  </div>

</body>
</html>

Here, I have taken a straightforward form to add the images. We need a functionality when we can populate the input field when we click add button. So first let us do that. We have used jQuery for that feature.

Step 3: Add jQuery code to populate input field.

After adding the jQuery code and some HTML code to insert dynamic input fields, our file looks like this.

<html lang="en">
<head>
  <title>Laravel Multiple File Upload Example</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
   

  <div class="container">

    <h3 class="jumbotron">Laravel Multiple File Upload</h3>
<form method="post" action="{{url('form')}}" enctype="multipart/form-data">
  {{csrf_field()}}

        <div class="input-group control-group increment" >
          <input type="file" name="filename[]" class="form-control">
          <div class="input-group-btn"> 
            <button class="btn btn-success" type="button"><i class="glyphicon glyphicon-plus"></i>Add</button>
          </div>
        </div>
        <div class="clone hide">
          <div class="control-group input-group" style="margin-top:10px">
            <input type="file" name="filename[]" class="form-control">
            <div class="input-group-btn"> 
              <button class="btn btn-danger" type="button"><i class="glyphicon glyphicon-remove"></i> Remove</button>
            </div>
          </div>
        </div>

        <button type="submit" class="btn btn-primary" style="margin-top:10px">Submit</button>

  </form>        
  </div>


<script type="text/javascript">

    $(document).ready(function() {

      $(".btn-success").click(function(){ 
          var html = $(".clone").html();
          $(".increment").after(html);
      });

      $("body").on("click",".btn-danger",function(){ 
          $(this).parents(".control-group").remove();
      });

    });

</script>


</body>
</html>

Step 5: Add the backend validation.

We are inserting multiple images so; we need to make array validation in our project. In a FormController.php file, add the following code to validate our input file.

// FormController.php

$this->validate($request, [
    'filename' => 'required',
    'filename.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);

It checks against the required field as well image type. If the input file does not contain image or jpg, png ,gif or svg then it throws an error and laravel catch it and display these errors in the frontend. To show errors in the form, we need to write the following code after container class.

// create.blade.php

      @if (count($errors) > 0)
      <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.<br><br>
        <ul>
          @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
      @endif

Okay, so here validation is done.

jQuery Dynamic Fields

Step 6: Insert multiple images in the database.

After checking the validation, we need to store the image names in our database. So our final code to insert the various images on the database is following.

Related Posts
1 of 39
// FormController.php

/**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)

    {

        $this->validate($request, [

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

        ]);
        
        if($request->hasfile('filename'))
         {

            foreach($request->file('filename') as $image)
            {
                $name=$image->getClientOriginalName();
                $image->move(public_path().'/images/', $name);  
                $data[] = $name;  
            }
         }

         $form= new Form();
         $form->filename=json_encode($data);
         
        
        $form->save();

        return back()->with('success', 'Your images has been successfully');
    }

If the input file is image then it will loop through all the images one by one and store the image names in the array and then insert that array in the database. I am using json_encode to insert the multiple image names in one row. You can make another table and then add the foreign key to that table. After success, we need to display a success message. So write that code in the create.blade.php file.

// create.blade.php

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

So, our final create.blade.php file looks like this.

// create.blade.php

<html lang="en">
<head>
  <title>Laravel Multiple File Upload Example</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
  <div class="container">
      @if (count($errors) > 0)
      <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.<br><br>
        <ul>
          @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
      @endif

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

    <h3 class="jumbotron">Laravel Multiple File Upload</h3>
<form method="post" action="{{url('form')}}" enctype="multipart/form-data">
  {{csrf_field()}}

        <div class="input-group control-group increment" >
          <input type="file" name="filename[]" class="form-control">
          <div class="input-group-btn"> 
            <button class="btn btn-success" type="button"><i class="glyphicon glyphicon-plus"></i>Add</button>
          </div>
        </div>
        <div class="clone hide">
          <div class="control-group input-group" style="margin-top:10px">
            <input type="file" name="filename[]" class="form-control">
            <div class="input-group-btn"> 
              <button class="btn btn-danger" type="button"><i class="glyphicon glyphicon-remove"></i> Remove</button>
            </div>
          </div>
        </div>

        <button type="submit" class="btn btn-primary" style="margin-top:10px">Submit</button>

  </form>        
  </div>


<script type="text/javascript">


    $(document).ready(function() {

      $(".btn-success").click(function(){ 
          var html = $(".clone").html();
          $(".increment").after(html);
      });

      $("body").on("click",".btn-danger",function(){ 
          $(this).parents(".control-group").remove();
      });

    });

</script>
</body>
</html>

I have already put this code on Github.

Github Repository

12 Comments
  1. 123 says

    You forgot to add use App\Form; in FormController.

    In case someone stumbles up here and is stuck

  2. virgil tudorancea says

    Perfect i was looking for this tutorials, everybody does it only for one image. Thanks mate.

  3. Rajkumar Shukla says

    Thanks for the post it’s very helpfull if possible provide the Demo option here.
    So after seeing the Demo we can save or time to it’s meeting or requirment or not.

  4. Jeff says

    Hi mate. Thanks for this great tutorial.
    Kindly, could you explain how one can retrieve the images? Thanks

  5. Kelly says

    Hello, Why is it saving only one image in the database?

    Regards

    1. Krunal says

      Nope, I guess you are having a mistake. It actually saves multiple images in the database as well as uploads on the server.

  6. nadeem says

    how to retrieve the data of json encode?
    for example i want to display the every image what should i do? i have tried json_decode but its not working properly on index method.

  7. Dominic says

    I have the same issue why is it saving only one image in the database? i use laravel 5.6 do you think is the problem ? thanks a lot.

    Dominic

    1. Krunal says

      It is saving multiple images, but it is stored in a json format. Check your database.

  8. Simon says

    please i have been stuck on this for a very long time, please could u tell me how to display this images in my view

  9. Ubaidillah says

    Thanks !
    but why when i’ve been uploaded 3 images, it’s only save one filename/json in the Database, but in public folder it’s work, they save all the 3 images ?

  10. Kunal Rajput says

    Below are some corrections i did , if anyone want files to be saved with different id , instead of array also added time() in $name so it will stop messing with different images with same name.

    // Controller

    public function store(Request $request)

    {

    $this->validate($request, [

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

    ]);

    if($request->hasfile(‘filename’))
    {

    foreach($request->file(‘filename’) as $image)
    {
    $form= new Form();

    $name=time().’.’.$image->getClientOriginalName();
    $image->move(public_path().’/images/’, $name);
    $data = $name;
    $form->filename=$data;
    $form->save();
    }

    }

    return back()->with(‘success’, ‘Your images has been successfully’);
    }

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.