File upload is a common task in web development. Laravel provides a simple and elegant way to handle file upload with validation. You can validate a file before uploading it on the server side. The file validation may contain mime type, size, etc. In this blog post, we will explore how to upload files with validation in Laravel 10. Previously, we handled image upload in Laravel 10 with Validation. In the same way, we will be handling file upload in this post. create a form in your Laravel 10 application that allows users to upload a file. To create a form, you can use the Laravel Collective HTML package, which provides a set of Laravel form helpers. Alternatively, you can use plain HTML to create your form. Here is an example of a simple form using Laravel Collective:
Prerequisites
We are going to implement the functionality of file upload in Laravel 10. Hence, you need a Laravel 10 application. However, in order to create a Laravel 10 project, below tools and configurations are required.
- 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.
Create a Project For File Upload in Laravel 10
For having Laravel 10 project setup, you need to hit the below command in the terminal. It will take a couple of minutes in order to finish the installation.
composer create-project --prefer-dist laravel/laravel file-upload
After the project setup, let’s connect it to a database.
Create and Configure a Database
For connecting the project with the Database, firstly, you need a database. So, create a database in MySQL. After that, navigate to the root of the project folder and look at the .env file.
Now, under the DB section, just update the DB 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}}
Once you complete the above step, your application is connected to the database.
Create a Model and Migration in Laravel 10
Next, you need to create a model and migration for the File upload functionality. The model will contain the mass assignment property through which we will be inserting the file name into the table.
php artisan make:model File -mc
The above command will create a model, a migration, and a controller. Now, you need to add the schema inside the migration.
<?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');
}
};
Next, you need to migrate the migration so that the table schema will be dumped out into the database.
php artisan migrate
How to Upload Image Using Ajax in Laravel 10 with Validation
Add Fillable Property in Model in Laravel 10
In the model, you will require to add the fillable property. The fillable property will validate the values respective to the fields to be inserted into the table.
<?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',
];
}
Now, you are ready to add the functionality for file upload in Laravel 10.
Add Functionality For File Upload in Laravel 10
You will have to add the below functions in the FileController.php. Through this controller, we will handle the form request with validation and also we will implement the file upload functionality.
Hence, take a look at the below snippet, and add it to the controller.
<?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([
'file' => 'required|mimes:pdf,csv,xls,xlsx,doc,docx|max:2048',
]);
$fileName = time().'.'.$request->file->extension();
$fileOriginalName = $request->file->getClientOriginalName();
$request->image->move(public_path('uploads'), $fileName);
$image = File::create([
"file_name" => $fileName,
'file_original_name' => $fileOriginalName,
]);
if ($image) {
return back()->with('success','Success! File has been uploaded');
}
else {
return back()->with("failed", "Alert! Unable to upload file");
}
}
}
Now, in the next step, you need to add routes for running the project to accomplish the file upload.
How to Upload Multiple Images with Validation in Laravel 10
Create Web Routes
For adding the web routes, navigate to the web.php file and then add the below routes.
<?php
use App\Http\Controllers\FileController;
use Illuminate\Support\Facades\Route;
Route::get('file', [FileController::class, 'create'])->name('file');
Route::post('file', [FileController::class, 'upload'])->name('file.store');
After adding the routes, lastly, you need to create a view for file upload in Laravel 10.
Create a View For File Upload Handling in Laravel 10
You have to create a view with the name file-upload.blade.php. After creating the view, add the below snippet in it.
<!doctype html>
<html lang="en">
<head>
<title> Laravel 10 File 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 File Upload with Validation</h4>
</div>
<div class="card-body">
<div class="form-group">
<label> File </label>
<input type="file" name="file" class="form-control @error('file') is-invalid @enderror ">
@error('file')
<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 it for the file upload functionality in Laravel 10.
Now, you can run the application and see the result of the file upload.
php artisan serve
Leave a Reply