Laravel Multiple Files Upload Example Step by Step

17
5345
Laravel Multiple Files Upload Tutorial With Example From Scratch

We are going to build multiple files upload system using Laravel. This tutorial will show you how to use laravel default validation with jQuery ajax in the frontend. The server validates all the inputs against defined validation, and if any of the validation is going to fail, it will redirect to our create page with error messages.

Laravel multiple files upload

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 if you use laravel validation for your web form in the laravel project.

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

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

After establishing the Laravel, configure the database. So go to the .env file and continue the database credentials.

Next, we need to 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 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 code and some HTML code, 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 file type. If the input file does not contain file or doc, pdf, docx, zip, it throws an error, and laravel catches it and demonstrates these errors in the frontend. 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

Okay, so here validation is done.

Laravel Multiple Files Validation Tutorial

Step 5: Insert multiple files into the database.

After checking the validation, we need to 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 one by one, 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

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('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>

Now, you can able to upload multiple files. But, of course, images and other file formats are not allowed.

Finally, our Laravel Multiple Files Upload Tutorial is over.

17 Comments

  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

  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.

  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

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

  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?

  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?

Leave A Reply

Please enter your comment!
Please enter your name here

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