How to Upload Multiple Files in Laravel

To upload multiple files upload in Laravel, use the “jQuery plugin” to populate the field and submit the server; on the backend, we use PHP’s forEach() function to loop through one by one file and upload it.

We will use a jQuery plugin to populate the file field and submit one server. Of course, it will always be excellent to use laravel validation for your web form in the laravel project.’

Here is the step-by-step guide to upload multiple files in Laravel.

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

Go to the .env file and continue the database credentials.

Next, we must create a migration file to store the image’s name. So go to the CMD and kick the following command.

php artisan make:migration create_files_table 

Define the schema as follows.

<?php

// create_files_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('files', function (Blueprint $table) {
            $table->increments('id');
            $table->string('filename');
            $table->timestamps();
        });
    }

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

Then migrate this schema and make a table in the database.

php artisan migrate

Step 2: Define the model, controller, and routes.

Hit the following command to generate the model and controller.

php artisan make:model File

php artisan make:controller FileController

It will generate two files.

  1. File.php
  2. FileController.php

Now define routes in routes >> web.php file and add the following routes.

// web.php

Route::get('file','FileController@create');
Route::post('file','FileController@store');

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

// FileController.php

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

Immediately, make a create.blade.php file inside the 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('file')}}" 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 natural form to add the files. However, we need functionality to populate the input field when clicking the button. So first, let us do that. We have used jQuery for that feature.

Step 3: Add jQuery code to populate the input field.

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

<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('file')}}" 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>

Laravel 5.5 Files Upload

Step 4: Add the backend validation.

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

// FileController.php

$this->validate($request, [

                'filename' => 'required',
                'filename.*' => 'mimes:doc,pdf,docx,zip'

]);

It validates against the required field as well as the file type. If the input file does not contain a file or doc, pdf, docx, or zip, it throws an error, and laravel catches it and demonstrates these errors in the front end. To show errors in the form, we need to write the following code after the 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

Here the validation is done.

Laravel Multiple Files Validation Tutorial

Step 5: Insert multiple files into the database.

After checking the validation, we must store the file names in our database. So our final code to insert the various files in the database is the following.

// FileController.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.*' => 'mimes:doc,pdf,docx,zip'

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

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

         $file= new File();
         $file->filename=json_encode($data);
         
        
        $file->save();

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

If the input is a file, it will loop through all the files individually, store the file names in the array, and then insert that array in the database. I am using json_encode to include the multiple filenames in one row.

You can make another table and then append 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

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('file')}}" 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>

That’s it.

17 thoughts on “How to Upload Multiple Files in Laravel”

  1. Thank you very much for the tutorial, please i have followed this step by step

    Please can you tell me how to display the images from the database to my views

    Reply
  2. Your tutorial are interesting but it would worth commenting your code inside the code. It would make it even better and easier to read.

    Reply
  3. Doesn’t work it shows array to string conversion and when i dd on $name=$file->getClientOriginalName(); it says Call to a member function getClientOriginalName() on array

    Reply
  4. why are you cloning file input using jQuery, instead of it you can simply use file input with multiple attribute as .

    Reply
  5. Hey, I want to add another coulumn with image file like name , address, date of birth, so where I have to change in..controller?, create.blade.php ? or jquery?

    Reply
  6. thank you for the example.
    it’s work for me but the problem is when i save, just save the first row.

    in the storage files, it’s work but in data table not, just the first row….

    any idea?

    Reply

Leave a Comment

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