In this article, we will see multiple file upload in Laravel 9 tutorial with an example. We can easily upload different types of files like .pdf
, .doc
, .docx
, .csv
, .txt
, .png
, .gif
, .zip
, etc. using the Laravel 9 multiple file upload. We will add the validation rules only to allow particular types of file formats in the Laravel. Let’s dive into it.
Step 1: Install Laravel 9
If you already have installed Laravel 9 on your local machine, you can skip this step. You can easily install the fresh version of Laravel 9 by running the below command in your terminal. You can give it any name but in this case, we will name it demo-app
.
composer create-project --prefer-dist laravel/laravel demo-app
or use the following command to install the specific Laravel version
composer create-project laravel/laravel:^9.0 demo_app
Notes: To install Laravel 9 you need PHP 8.0. So make sure you have installed PHP 8.0 in your local WAMP, LAMP, MAMP, etc.
Step 2: Create Migration
Now, we will create a files
table using the Laravel migrations. Let’s run the below command to create a migration.
cd demo-app
php artisan make:migration create_files_table --create=files
After running the above command a new migration file will be created in “database/migrations” directory.
database/migrations/2022_06_07_182739_create_files_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFilesTable extends Migration
{
public function up()
{
Schema::create('files', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('files');
}
}
Now, run the below command to create database tables.
php artisan migrate
Step 3: Create A Model
In this step, we will create File
model which helps us to connect with the files
table so that we can perform the database operations using the model. Run the below command to create a model.
php artisan make:model File
Then the new file will be created in demo-app/app/Models/File.php
. In the model add the name field in the fillable array.
app/Models/File.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
use HasFactory;
protected $fillable = [
'name'
];
}
Step 4: Create MultipleFileUploadController
Let’s create a MultipleFileUploadController
and let’s add those two methods that we have added in the routes file getFileUploadForm()
and store()
.
app/Http/Controllers/MultipleFileUploadController.php
<?php
namespace App\Http\Controllers;
use App\Models\File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class MultipleFileUploadController extends Controller
{
public function getFileUploadForm()
{
return view('multiple-file-upload');
}
public function store(Request $request)
{
$request->validate([
'documents' => 'required',
'documents.*' => 'required|mimes:doc,docx,xlsx,xls,pdf,zip,png,bmp,jpg|max:2048',
]);
if ($request->documents){
foreach($request->documents as $file) {
$fileName = $file->getClientOriginalName();
$filePath = 'uploads/' . $fileName;
$path = Storage::disk('public')->put($filePath, file_get_contents($file));
$path = Storage::disk('public')->url($path);
// // Create files
File::create([
'name' => $fileName
]);
}
}
return back()
->with('success','Files have been successfully uploaded.');
}
}
Notes: To validate .doc, .docx, .xlsx, .xls
you need to create mimes.php
in config
directory and add the following content.
config/mimes.php
<?php
return [
'doc' => array('application/msword', 'application/vnd.ms-office'),
'docx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip'),
'xlsx' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
'xls' => array('application/vnd.ms-excel'),
];
You can find common MIME types here.
Step 5: Create Routes
We need to add two routes in routes/web.php
file to perform the Laravel 9 multiple images upload. The first GET
route is to show the image upload form and another route for the POST
method to store the image in Laravel.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\MultipleFileUploadController;
Route::get('multiple-file-upload', [ MultipleFileUploadController::class, 'getFileUploadForm' ])->name('get.multipleFileupload');
Route::post('multiple-file-upload', [ MultipleFileUploadController::class, 'store' ])->name('store.multiple-files');
Step 6: Create Blade/HTML File
At last, we need to create a multiple-file-upload.blade.php
file in the views folder, and in this file, we will add the multiple-file upload form HTML.
resources\views\multiple-file-upload.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 9 Multiple File Upload Tutorial With Example - ScratchCode.io</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading mb-3 mt-5">
<h2>Laravel 9 Multiple File Upload Tutorial With Example - ScratchCode.io</h2>
</div>
<div class="panel-body">
@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>
@endif
@if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form action="{{ route('store.multiple-files') }}" method="POST" enctype="multipart/form-data">
@csrf
<div class="row">
<div class="mb-3 col-md-6">
<label class="form-label">Select Files:</label>
<input type="file" name="documents[]" class="form-control" multiple/>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-success">Upload Files...</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Step 7: Output – Laravel 9 Multiple File Upload With Example
Hurray! We have completed all steps for the Laravel 9 multiple files upload tutorial with an example. Let’s run the below command and see how it’s working.
php artisan serve
After running the above command, open your browser and visit the site below URL:
http://127.0.0.1:8000/multiple-file-upload
Notes: You can find the uploaded file in storage/app/public/uploads
the directory. Please note that the storage public folder is publicly available so if you want to keep files private then use the “local” disk driver like Storage::disk('public')
Additionally, read our guide:
- Laravel 9 Image Upload Tutorial With Example
- Laravel 9 Multiple Database Connections Example
- Laravel 9 Automatically Generates Sitemap With Example
- Make Model In Laravel 9 Tutorial With Example
- Laravel Firebase Tutorial With Example
- Laravel 9 Multiple Images Upload Example
- Laravel Remove Column From Table In Migration
- Show All Fields Of Model In Django Admin
- Laravel: Increase Quantity If Product Already Exists In Cart
- How To Update Pivot Table In Laravel
- How To Install Vue In Laravel 8 Step By Step
- How To Handle Failed Jobs In Laravel
- Best Ways To Define Global Variable In Laravel
- How To Get Latest Records In Laravel
- Laravel Twilio Send SMS Tutorial With Example
- How To Pass Laravel URL Parameter
- Set Default Value Of Timestamp In Laravel Migration
- Laravel 9 File Upload Tutorial With Example
- How To Schedule Tasks In Laravel With Example
- Laravel Collection Push() And Put() With Example
That’s it from our end. We hope this article helped you to learn Laravel 9 multiple file upload tutorial with an example.
Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post 🙂 Keep Smiling! Happy Coding!