To upload multiple files in Laravel, use the “jQuery plugin” to populate the field and submit the server; on the backend, we will use the forEach() function to loop through 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:
Step 1: Setup the Laravel
composer create-project laravel/laravel multiplefiles --prefer-dist
Go to the .env file and continue the database credentials.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=8889 DB_DATABASE=multiplefiles DB_USERNAME=root DB_PASSWORD=root
Next, we must create a migration file to store the image’s name.
Go to the terminal or cmd and kick the following command.
php artisan make:migration create_files_table
Define the schema as follows.
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('files', function (Blueprint $table) { $table->id(); $table->string('filename'); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('files'); } };
Then, migrate this schema and make a table in the database.
php artisan migrate
Step 2: Configure Bootstrap CSS and jQuery
To use Bootstrap CSS in Laravel 11, you need to install the laravel/ui package.
Go to the root of your Laravel project, open the terminal or cmd, and type the following command.
composer require laravel/ui
Now, install the frontend scaffolding using the ui Artisan command:
php artisan ui bootstrap
Now, install the jQuery using this command:
npm install jquery
And then install the remaining packages using this command:
npm install
Now, go to the resources >> js >> app.js file and import the jQuery like this:
import './bootstrap'; import $ from 'jquery'; window.jQuery = window.$ = $;
Save this file, go to the terminal, and compile our fresh scaffolding using these commands:
npm run dev
We will use the @vite directive to include all the Bootstrap CSS, JS, and jQuery files in our project later.
Step 3: Define the model, controller, and routes.
Let’s create a model and controller file using the below commands:
php artisan make:model File php artisan make:controller FileController
It will generate two files.
- File.php: It is a model file.
- FileController.php: It is a controller file.
Define routes in routes >> web.php file and add the following routes.
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\FileController; Route::get('/', function () { return view('welcome'); }); Route::get('file', [FileController::class, 'create']); Route::post('file', [FileController::class, 'store']);
In the FileController, we will add a create() function and write the following code.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\File; class FileController extends Controller { public function create() { return view('create'); } }
Here, we imported the File.php model, which we will use to insert the file name into the database.
Step 4: Create a master layout file
Inside the resources >> views folder, create a master layout file called “layout.blade.php” and add the below code.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Laravel Multiple Files Upload</title> @vite(['resources/sass/app.scss', 'resources/js/app.js']) </head> <body> <div class="container"> @yield('content') </div> </body> </html>
You can see here that we used the @vite directive to import all the CSS and JS files in our project inside the <head> tag. Now, Bootstrap JS and jQuery are included in our project.
We will inherit this file in the different views files so that all files have access to CSS and JS scripts.
Step 5: Create a form that accepts multiple files as input
Inside the resources >> views folder, create a new file called “create.blade.php” and add the below code.
@extends('layout') @section('content') <h3>Laravel Multiple Files Upload</h3> @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 <form method="post" action="{{ url('file') }}" enctype="multipart/form-data"> @csrf <div class="input-group mb-3"> <input type="file" name="filename[]" class="form-control"> <button class="btn btn-success add-btn" type="button"> <i class="bi bi-plus-lg"></i> Add </button> </div> <div class="clone d-none"> <div class="input-group mb-3"> <input type="file" name="filename[]" class="form-control"> <button class="btn btn-danger remove-btn" type="button"> <i class="bi bi-dash-lg"></i> Remove </button> </div> </div> <button type="submit" class="btn btn-primary mt-2"> Upload </button> </form> <script type="module"> $(document).ready(function() { // When the 'Add' button is clicked $("body").on("click", ".add-btn", function() { var clone = $(".clone").clone(true).removeClass('clone d-none'); // Clone and remove 'clone' and 'd-none' classes $(this).closest(".input-group").after(clone); // Insert the cloned element after the current input group }); // When the 'Remove' button is clicked $("body").on("click", ".remove-btn", function() { $(this).closest(".input-group").remove(); // Remove the closest parent input group }); }); </script> @endsection
In this code, we are using Bootstrap CSS form for the overall layout and using jQuery to populate the input field. Save the file and go to this URL:http://localhost:8000/file
This is the basic form to upload a single file.
If you click on the “Add” button, the input field will start populating it like this:
Step 6: Add the backend validation.
We are inserting multiple files, so we need to validate an array of input files.
In a FileController.php file, create a store() function and add the below code inside it.
public function store(Request $request) { $request->validate([ 'filename' => 'required', 'filename.*' => 'mimes:doc,pdf,docx,zip' ]); }
Here, 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.
We have already written the code in the create.blade.php file to display the errors like this:
Step 7: Uploading multiple files and save the details into a database
After checking the validation, we will upload the multiple files into the public >> files folder and save the file details into the database.
Here is the complete code for the FileController.php file:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\File; class FileController extends Controller { public function create() { return view('create'); } public function store(Request $request) { $request->validate([ 'filename' => 'required', 'filename.*' => 'mimes:doc,pdf,docx,zip|max:2048' ]); if ($request->hasfile('filename')) { foreach ($request->file('filename') as $file) { $name = time() . '_' . $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 an array of files, it will loop through all the files individually, move the file into the public >> files folder, and then insert the filename in the database.
I am using the json_encode() function to include multiple filenames in one row.
You can make another table and then append the foreign key to that table.
If you upload the file successfully, you will see something like this:
Now, head over to the phpmyadmin (MySQL database) and see if the file details are saved in the database:
Let’s see the uploaded files on the server.
Go to the public >> files folder, and you will see these files.
That’s it.
Simon imoh
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
Krunal
Although this tutorial is all about files and not images, I can certainly help you with this. Just use and pass the public_path up to your image names, use the names, and display it on the front end.
Simon imoh
good afternoon,
i previously wrote asked for how to use a loop to display the saved image, but you have not replied
Krunal
Although this tutorial is all about files and not images, I can certainly help you with this. Just use and pass the public_path up to your image names, use the names, and display it on the front end.
James Nakason
Thank you very much. I am still new to Laravel …
Krunal
Thanks man!
chris
Your tutorial are interesting but it would worth commenting your code inside the code. It would make it even better and easier to read.
Krunal
Thanks, will try my best to add the comments inside the code in future posts.
Praneet Singh Roopra
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
someStranger
it means that your $file has no value
Krunal
Correct!
Nadia
Thank you very much for the tutorial, can u make tutorial how to display the stored file in blade?
as u stored these in array.
Krunal
Will try to create a new tutorial and display those files!
Reno Rahardi
How to view files that have just been uploaded?
Dava
to have image and other files can be upload, just change the validate request of the filename* right?
Hein Thu Ya
How to display pdf file on the frontpage
Haritsinh Gohil
why are you cloning file input using jQuery, instead of it you can simply use file input with multiple attribute as .
jhon
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?
maw maw
you must be solve this problem
SANN
try again to solve this problem about your solution
So, I can wait for replying your answer
Jose María
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?
ZHAFARI IRSYAD
I got error, array to string conversion