You can upload multiple files in Laravel 9. The files can be validated using the Laravel validation rules. While uploading multiple files, you can have an array of files. The form will be used to select multiple files. The controller will have the functionality to read and handle the files. The array of files will be extracted and then uploaded. We have already seen the single file upload in Laravel 9.
We will add the file validation, so, the validation result will be shown like this.
This will accept only files having mime type – pdf, csv, xls, xlsx, doc, docx. Once, you select the appropriate file(s) as shown below.
On successful upload, it will show the below success result.
So, we are going to cover the above results in this post. Therefore, let’s dive into the post.
Prerequisites
For uploading multiple files, you will need to create a project in Laravel 9.
- PHP >=8.0.2
- Composer
- Apache/Nginx Server
- VS Code Editor (Optional)
- MySQL (version > 5)
Create a Project in Laravel 9 For Multiple File Upload
This step is not required if you already have a project setup. If not then you can create a new project.
composer create-project --prefer-dist laravel/laravel blog
Once the project is created, you can configure the database for it.
How to Upload Image in Laravel 9 with Validation
Create and Configure Database
For database configuration, you will have to navigate to the .env file. Under the database section, you can add the database credentials as shown below.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=DATABASE_NAME
DB_USERNAME=DATABASE_USERNAME
DB_PASSWORD=DATABASE_PASSWORD
In the next step, you have to move to the functionality part.
Form Validation in Laravel 9 with Custom Error Messages
Model, Migration, and Controller to Upload Multiple File
In this step, we will create a migration, a model, and a controller. All the files can be created using a single command.
php artisan make:model File -mc
After creating the files, let’s navigate to the created migration file.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('files', function (Blueprint $table) {
$table->id();
$table->string('fileName');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('files');
}
};
Next step, we will migrate the database schema. For migrating the database, you will have to hit the below command.
php artisan migrate
After migrating the schema, let’s add the mass assignment to the model.
How to Create a CRUD Application in Laravel 9 From Scratch
Add Mass Assignment in the Model
Navigate to the mode and add the fillable property as shown below.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
use HasFactory;
protected $fillable = [
'fileName'
];
}
Now, you will need to add the functionality for multiple file uploads.
Create REST API in Laravel 8 Using JWT Authentication
Add Functionality For Multiple File Upload
For adding multiple file upload functionalities, you have to navigate to the controller. We already created the controller as FileController.php. So, let’s add the below snippet.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\File;
class FileController extends Controller
{
/**
* Return file upload view
* @param request
* @return response
*/
public function index() {
return view('file-upload');
}
/**
* Upload file
* @param request
* @return response
*/
public function upload(Request $request) {
$request->validate([
'files' => 'required',
'files.*' => 'mimes:pdf,csv,xls,xlsx,doc,docx|max:2048'
]);
$files = [];
$uploadStatus = [];
if ($request->hasfile('files')) {
foreach($request->file('files') as $file) {
$name = time().rand(1,100).'.'.$file->extension();
if ($file->move(public_path('uploads'), $name)) {
$files[] = $name;
$uploadStatus = File::create(["fileName" => $name]);
}
}
}
if ($uploadStatus) {
return back()->with('success', 'Success! file uploaded');
}
else {
return back()->with('failed', 'Alert! file not uploaded');
}
}
}
In the next step, we will add routes for multiple file uploads.
How to Create Github Login in Laravel 8 Using Socialite
Add Routes For Multiple File Upload
For adding routes, you can navigate to the web.php file.
<?php
use App\Http\Controllers\FileController;
use Illuminate\Support\Facades\Route;
Route::get('file', [FileController::class, 'index'])->name('file');
Route::post('file', [FileController::class, 'upload'])->name('file');
In the last step, you will have to create a view for having a form.
How to Create Login with Twitter in Laravel 8 Using Socialite
Create a View For Multiple File Upload
Create a view with the name file-upload.php and then add the below snippet.
<!doctype html>
<html lang="en">
<head>
<title> Laravel 9 Multiple Files Upload - 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') }}" method="POST" enctype="multipart/form-data">
@csrf
<div class="card shadow">
@if(Session::has('success'))
<div class="alert alert-success alert-dismissible">
<button type="button" class="btn-close" data-dismiss="alert">×</button>
{{Session::get('success')}}
</div>
@elseif(Session::has('failed'))
<div class="alert alert-danger alert-dismissible">
<button type="button" class="btn-close" data-dismiss="alert">×</button>
{{Session::get('failed')}}
</div>
@endif
<div class="card-header">
<h4 class="card-title fw-bold"> Laravel 9 Multiple Files Upload </h4>
</div>
<div class="card-body">
<label for="file"> File(s) <span class="text-danger">*</span> </label>
<input type="file" name="files[]" multiple class="form-control @error('files') is-invalid @enderror">
@error('files')
<div class="invalid-feedback">{{ $message }} </div>
@enderror
</div>
<div class="card-footer">
<button type="submit" class="btn btn-success"> Upload </button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Now, it’s time to check the result of the application.
Conclusion
As a result, we achieved the multiple files upload functionality. We added a validation rule for checking the required mime type. You can add any specific validation rule accordingly. That’s it for this post. I hope you will find helpful to this post.
Leave a Reply