Are you a beginner developer? Are you trying to get the hang of file upload? Are you confused about how file upload works? Do you want to have more understanding of java points?
No more worry because this article will be introducing you to something new, something to help elevate you from a beginner to a pro. Something as simple as a Laravel file upload.
File upload is a day-to-day activity that anybody on any social media can carry out on Twitter, Facebook, or Instagram.
Now, tell me – have you ever gone through the anger and panic attack that follows when you cannot successfully upload a file?
The files get stuck or have a hindrance from going through. What do you do when you find yourself in this situation?
Join me and read this article as you learn some essential tips on how a PHP web framework called Laravel file upload can help you escape this situation.
Let’s break this down by explaining what Laravel is.
Laravel is a free, open-source PHP web framework used to develop web applications.
It has the model–view controller as an architectural pattern that allows you to build web applications more efficiently and straightforwardly. It is a creation of Taylor Otwell.
Now we know what Laravel is, let’s move to the subject matter; Laravel file upload.
Laravel file upload is how files are uploaded from a user system to the server. These files can be photos and documents.
When a file is uploaded to the server, Laravel sends the file to the storage app by default. Why? It is to protect it from illegal access or scraping.
A typical scenario is where you are asked to upload a photo on Facebook. Then, you choose a picture from your device (user system), and once you have done that, you press the submit button, which sends the image you chose to another system (Facebook server).
So, it deals with sending documents (photos, videos, audios, etc.) from one system to a server system.
Laravel file upload is relatively easy. You need to create a view file (user interface) where a user can select a file to be uploaded and a controller where uploaded files will be processed.
These uploaded files are stored in the storage/app folder by default.
Form::file('file_name');
In Form::open(), you need to add ‘files’ =>’ true’ as shown below. This will enable the form to be uploaded in multiple parts.
Form::open(array('url' => '/uploadfile','files'=>'true')
The code has a table called forms that contains the id, path, created_at, and updated_at.
1. The first step is to create a project first. First, open the command-line tool from the start menu and execute the following command to create a Laravel project from scratch.
composer create-project laravel/laravel --prefer-dist laravel-file-upload
2. Create a database configuration, e.g. name, password, etc., use MAMP or XAMPP as a local web server, define a database name in MySQL, and add the correct formatting in the .env file.
3. Install the Laravel package.
cd laravel-file-upload
4. Create a model and migration. Store the uploaded file information, and open a migration file to define the table values in the database.
php artisan make:model File -m
Then, go to database/migrations/timestamp_create_files_table file and define the table values.
<?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');
}
5. Create two routes. Go to routes (web.php) and create two routes. The first route handles the form creation, whereas the second route stores the file in the MySQL database.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FileUpload;
/*
Web Routes
Here is where you can register web routes for your application. The RouteServiceProvider loads these routes within a group that 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')
6. Generate a controller. Follow these steps to create a file upload controller that defines the business logic for file uploads and storage in Laravel. Execute this command to create the controller:
PHP artisan make:controller FileUpload
Open the app/Http/Controllers/FileUpload.php file. Here you define the two methods that handle the file upload. The first method renders the view via the FileUpload controller, and the second, the fileUpload() method, checks the validation, mime type, or file size limitation.
This method also stores the file in your storage/public/uploads folder and saves your database’s file name and path.
<?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);
}
}
}
Finally, generate a two-blade view. To create a blade file, start creating a view and the file upload form. Create a resources\views\file-upload.blade.php file, then place the following code inside it:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<title>Laravel File Upload</title>
<style>
.container {
max-width: 500px;
}
dl, ol, ul {
margin: 0;
padding: 0;
list-style: none;
}
</style>
</head>
<body>
<div class="container mt-5">
<form action="{{route('fileUpload')}}" method="post" enctype="multipart/form-data">
<h3 class="text-center mb-5">Upload File in Laravel</h3>
@csrf
@if ($message = Session::get('success'))
<div class="alert alert-success">
<strong>{{ $message }}</strong>
</div>
@endif
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<div class="custom-file">
<input type="file" name="file" class="custom-file-input" id="chooseFile">
<label class="custom-file-label" for="chooseFile">Select file</label>
</div>
<button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
Upload Files
</button>
</form>
</div>
</body>
</html>
Pros
Cons
Laravel considers strict security while handling file uploads, unlike vanilla PHP. It is flexible.
Ready to get started with Laravel File Upload? Visit Filestack today to get registered for free.