Similar to the image, you can upload the file in Laravel 9. In the file, you can upload pdf, CSV, Excel, etc. You can set the validation rules for every type of file. This can make the file upload secure. It is always recommended to validate and sanitize the file before uploading. In this post, we will see the file upload. But, before uploading, we will validate the file in Laravel 9.
We are going to achieve the below results in this post.
We will set the validation for the required field. In the result, it will throw the validation error as shown below.
We will validate the file using validation rules. It will help to detect the file using its extension.
If the file is uploaded successfully, it will return the success response.
So, let’s move the functionality of file upload in Laravel 9.
Prerequisites
For implementing the file upload in Laravel 9, you will require the below configurations.
- PHP >=8.0.2
- Composer
- Apache/Nginx Server
- VS Code Editor (Optional)
- MySQL (version > 5)
Create Project in Laravel 9 to Upload File
It is not recommended to create a new project if you already have a project.
composer create-project --prefer-dist laravel/laravel blog
After having the project, connect your project with a database.
Configure Database in Laravel 9
For the database configuration, navigate to the .env file. Now, add the database credentials.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=DATABASE_NAME
DB_USERNAME=DATABASE_USERNAME
DB_PASSWORD=DATABASE_PASSWORD
Pass Data to Master Layout By Service Provider in Laravel 8
Create a Model, Migration, and Controller to Upload File
You can create a model, migration, and controller using the below command.
php artisan make:model File -mc
At very first, you have to add the schema for the table. Hence, open the created migration file. Now, add the schema as shown below.
<?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');
}
};
In the next step, you have to migrate this schema. For migrating the table(s) hit the below command.
php artisan migrate
Next, you have to add a mass fillable property to the model.
Add Fillable Data in Model in Laravel 9
Open the created model, 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'
];
}
Next, you will have to write the functionality to upload a file.
Upload File in Laravel 9
We will read the file from the input and then we will validate the file. After successful validation of the file, it will be uploaded. At last, we will store the filename into the table.
<?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([
'file' => 'required|mimes:pdf,csv,xls,xlsx,doc,docx|max:2048',
]);
if ($request->hasfile('file')) {
$file = $request->file('file');
$name = time().rand(1,100).'.'.$file->extension();
if ($file->move(public_path('uploads'), $name)) {
$files[] = $name;
$result = File::create(["fileName" => $name]);
}
}
if($result) {
return back()->with('success', 'Success! file uploaded');
}
else {
return back()->with('failed', 'Alert! file not uploaded');
}
}
}
Add Routes in Laravel 9
Next, you have to add the below routes in 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');
At last, you have to create a view for uploading the file.
Create a View For File Upload
You have to create a view with the name file-upload.blade.php. After creating the file, you have to add the below snippet.
<!doctype html>
<html lang="en">
<head>
<title> Laravel 9 File 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 File Upload </h4>
</div>
<div class="card-body">
<label for="file"> File <span class="text-danger">*</span> </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 class="card-footer">
<button type="submit" class="btn btn-success"> Upload </button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
That’s it for the functionality. Now, you can run the application to see the result.
Conclusion
We uploaded the file by validating the file type. You can validate a file in Laravel 9 by checking mime type as we did in this post. I hope this will be helpful for you while uploading any files.
Leave a Reply