Bước 4: Tạo lệnh php artisan storage:link bằng route
Laravel 9 File Upload Tutorial: Validation + Store in Database
Last updated on: November 25, 2022 by Digamber4.4MSee What's New in Ubuntu MATE 20.04 LTS [Desktop Tour]This is a step by step Laravel File Upload tutorial with example, and In this tutorial, we will learn how to upload files in Laravel with basic validation in MySQL database.
This tutorial will cover Laravel file uploading concepts:
Laravel project Installation
Route creation and configuration
Blade file creation
Database migration in Laravel
Implement validation on file uploading component
File uploading status via displaying messages
Allow uploading only specific file types. e.g .csv, .txt, .xlx, .xls, .pdf with file size limitation max upto 2MB
In this Laravel file upload example tutorial, we will generate two routes one for creating a form with getting method and another route for file uploading or post file upload data.
We develop a simple form using Bootstrap and its Form UI component.
It will allow us to choose a file that needs to be uploaded in the storage > public > uploads folder. We will also configure the database model and store the file path along with its name in the MySQL database.
Install Laravel Project
Open command-line tool and execute the following command to create a Laravel project from scratch.
BashCopy
Get into the freshly installed laravel project’s directory.
BashCopy
Connect to Database
You can use MAMP or XAMPP as a local web server for uploading files to storage in laravel. Define a database name in MySQL and add the correct configuration in .env file.
PL/SQLCopy
If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.
BashCopy
Create File Model & Configure Migrations
Create a Model in laravel, It holds the data definition that interacts with the database.
BashCopy
Next, open migration file for defining the table values in the database for storing the uploaded file’s information. Go to database/migrations/timestamp_create_files_table file and define the table values.
PHPCopy
Now, add the $fillable property in the File model. Open app/Models/File.php file and place the following code.
PHPCopy
Now, you are all set to run the migration. You can also see the update in the mysql database.
BashCopy
Laravel File Upload Example
Create Routes in Laravel
Go to routes/web.php and create two routes. First, the route handles the form creation, and the second route stores the file in the MySQL database.
PHPCopy
Create File Upload Controller
Create a file uploading controller; we define the business logic for uploading and storing files in Laravel.
Execute the command to create the controller.
BashCopy
Open app/Http/Controllers/FileUpload.php file, and we need to define the two methods to handle the file upload.
The first method renders the view via FileUpload controller, and the fileUpload() method checks the validation, be it required, mime type or file size limitation.
This method also stores the file into storage/public/uploads folder and saves the file name and path in the database.
PHPCopy
Create Blade File in Laravel
In this step, we will create a view along with the file uploading form.
Create resources\views\file-upload.blade.php file and place the following code inside of it.
PHPCopy
This code is responsible for showing file uploading form and also display the message based on the status.
<?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')->nullable();
$table->string('file_path')->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('files');
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
use HasFactory;
protected $fillable = [
'name',
'file_path'
];
}
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FileUpload;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/upload-file', [FileUpload::class, 'createForm']);
Route::post('/upload-file', [FileUpload::class, 'fileUpload'])->name('fileUpload');
Route::get('/use-file', [FileUpload::class, 'use_file']);
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\File;
class FileUpload extends Controller
{
public function createForm()
{
return view('file-upload');
}
public function fileUpload(Request $req)
{
$req->validate([
'file' => 'required|mimes:csv,txt,xlx,xls,pdf,jpg,png|max:20048'
]);
$fileModel = new File;
if ($req->file()) {
$fileName = time() . '_' . $req->file->getClientOriginalName();
$filePath = $req->file('file')->storeAs('uploads', $fileName, 'public');
$fileModel->name = time() . '_' . $req->file->getClientOriginalName();
$fileModel->file_path = '/storage/' . $filePath;
$fileModel->save();
return back()
->with('success', 'File has been uploaded.')
->with('file', $fileName);
}
}
public function use_file()
{
$files = File::all();
return view('use-file')->with(compact('files'));
}
}
<?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')->nullable();
$table->string('file_path')->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('files');
}
}
<?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')->nullable();
$table->string('file_path')->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('files');
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
use HasFactory;
protected $fillable = [
'name',
'file_path'
];
}
php artisan migrate
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FileUpload;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/upload-file', [FileUpload::class, 'createForm']);
Route::post('/upload-file', [FileUpload::class, 'fileUpload'])->name('fileUpload');
php artisan make:controller FileUpload
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\File;
class FileUpload extends Controller
{
public function createForm(){
return view('file-upload');
}
public function fileUpload(Request $req){
$req->validate([
'file' => 'required|mimes:csv,txt,xlx,xls,pdf|max:2048'
]);
$fileModel = new File;
if($req->file()) {
$fileName = time().'_'.$req->file->getClientOriginalName();
$filePath = $req->file('file')->storeAs('uploads', $fileName, 'public');
$fileModel->name = time().'_'.$req->file->getClientOriginalName();
$fileModel->file_path = '/storage/' . $filePath;
$fileModel->save();
return back()
->with('success','File has been uploaded.')
->with('file', $fileName);
}
}
}