Laravel is a popular PHP web framework that offers a wide range of features to make web development easier and faster. One of its key features is its ability to handle file uploads. Similar to a single file upload, you can upload multiple files in Laravel 10. The process of uploading multiple files is almost the same. The measure difference is in reading multiple files from the request object. You will need to extract files one by one from the request array. The request object will contain the files in the array form. In this article, we will discuss how to upload multiple files in Laravel 10.
Prerequisites
Basically, we are going to achieve the functionality to upload multiple files in Laravel 10. In order to proceed with Laravel 10, you will have a Laravel 10 application. However, for creating a Laravel 10 project, you need below tools and configurations.
- PHP >=8.1
- Composer
- Apache/Nginx Server
- VS Code Editor (Optional)
- MySQL (version > 5)
Once, you are ready with the above requirement, you can create a Laravel 10 project.
I am assuming, you are already ready with a Laravel 10 project with the database configuration. That’s why I am skipping the first step and directly jumping to the next step.
How to Upload a File with Validation in Laravel 10
Create a Model and Migration For Multiple Files Upload
For handling the multiple file upload in Laravel and saving the file name into the database, you will need a migration and model.
By using the migration, you will be able to create a schema for a table in which you will be storing the file name. So, let’s create it using the below command.
php artisan make:model File -mc
The above command will generate all three files which are – migration, model, and controller.
After creating the migration, you need to add the below schema inside it.
<?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('file_name')->nullable();
$table->string('file_original_name')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('files');
}
};
A basic schema for file upload in Laravel 10 is added now. However, you can add more fields in this schema as per your need.
Now, in the next step, you will need to migrate the above schema using the below command.
php artisan migrate
After migrating the schema, you need to add the fillable property for the mass assignment in the model.
PHP 8.2 New Features and Improvements – All You Need to Know
Add Mass Assignment for Multiple Files Upload in Laravel 10
Navigate to the created model and add the below snippet for the mass assignment.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
use HasFactory;
protected $fillable = [
'file_name',
'file_original_name',
];
}
Add Functionality to Upload Multiple Files in Laravel 10
In this step, you need to add the functionality to upload multiple files. Hence, look back to the controller and add the below snippet.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\File;
class FileController extends Controller
{
/**
* Display a listing of the resource.
*/
public function create()
{
return view('file-upload');
}
/**
* Upload file and save file name.
*/
public function upload(Request $request) {
$request->validate([
'files' => 'required',
'files.*' => 'required|mimes:pdf,csv,xls,xlsx,doc,docx|max:2048',
]);
$files = [];
if ($request->hasfile('files')) {
foreach ($request->file('files') as $file) {
$fileName = time().rand(1,100).'.'.$file->extension();
$fileOriginalName = $file->getClientOriginalName();
if ($file->move(public_path('uploads'), $fileName)) {
$files[] = $fileName;
File::create([
"file_name" => $fileName,
'file_original_name' => $fileOriginalName,
]);
}
}
}
if (count($files) > 0) {
return back()->with('success','Success! File(s) has been uploaded');
}
else {
return back()->with("failed", "Alert! Unable to upload file");
}
}
}
Next, respective to the above functions, you need to create routes.
How to Upload Multiple Images in Laravel 10 Using Ajax
Add Web Routes in Laravel 10
For adding the routes, navigate to the routes folder, and under that, look at the web.php file. Inside the file, put the below routes.
<?php
use App\Http\Controllers\FileController;
use Illuminate\Support\Facades\Route;
Route::get('files', [FileController::class, 'create'])->name('files');
Route::post('files', [FileController::class, 'upload'])->name('files.store');
At last, you need a view in which you will handle the file array in the form request.
Create a View For File Upload
You will require a view with the name file-upload.blade.php. Hence, after creating the view, simply add the below snippet inside it.
<!doctype html>
<html lang="en">
<head>
<title> Laravel 10 Multiple Files Upload with Validation - Programming Fields</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
</head>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-xl-6 col-md-6 col-sm-12 m-auto">
<form action="{{ route('file.store') }}" method="POST" enctype="multipart/form-data">
@csrf
<div class="card shadow">
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
<symbol id="check-circle-fill" fill="currentColor" viewBox="0 0 16 16">
<path
d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z" />
</symbol>
<symbol id="exclamation-triangle-fill" fill="currentColor" viewBox="0 0 16 16">
<path
d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-2z" />
</symbol>
</svg>
{{-- Display alert message --}}
@if (Session::has('success'))
<div class="alert alert-success alert-dismissible d-flex align-items-center" role="alert">
<svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Success:">
<use xlink:href="#check-circle-fill" />
</svg>
<div>
{{ Session::get('success') }} <button type="button" class="btn-close" data-bs-dismiss="alert"
aria-label="Close"></button>
</div>
</div>
@elseif (Session::has('error'))
<div class="alert alert-danger d-flex alert-dismissible align-items-center" role="alert">
<svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Danger:">
<use xlink:href="#exclamation-triangle-fill" />
</svg>
<div>
{{ Session::get('error') }} <button type="button" class="btn-close" data-bs-dismiss="alert"
aria-label="Close"></button>
</div>
</div>
@endif
<div class="card-header">
<h4 class="card-title fw-bold"> Laravel 10 Multiple Files Upload with Validation</h4>
</div>
<div class="card-body">
<div class="form-group">
<label> File </label>
<input type="file" name="files[]" class="form-control @error('files') is-invalid @enderror ">
@error('files')
<div class="invalid-feedback">{{$message}}</div>
@enderror
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-primary"> Upload </button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
That’s all done for the multiple files upload in Laravel 10. Now, you are ready to go with the result. Hence, run the application to see the result.
php artisan serve
Final Words
We achieved multiple files upload in Laravel 10 with a basic example. Also, we added the server-side validation rules for validating the files before upload. I hope you this post will help you at the basic level of uploading multiple files in Laravel 10.
Leave a Reply