Creating a file uploader in Laravel involves setting up a form to allow users to select and upload files, handling the file upload in the controller, and storing the uploaded files in the filesystem or cloud storage. Here's a basic guide to create a file uploader in Laravel:
Create a Blade view file (upload.blade.php
) in the resources/views
directory to display the file upload form:
<!-- upload.blade.php -->
<!DOCTYPE html>
<html>
<head>
<title>File Uploader</title>
</head>
<body>
<h2>Upload File</h2>
<form action="{{ route('upload.file') }}" method="post" enctype="multipart/form-data">
@csrf
<input type="file" name="file" required>
<button type="submit">Upload</button>
</form>
</body>
</html>
Define a route to handle the file upload request in routes/web.php
:
// routes/web.php
use App\Http\Controllers\FileUploadController;
Route::get('/upload', [FileUploadController::class, 'showUploadForm'])->name('upload.form');
Route::post('/upload', [FileUploadController::class, 'uploadFile'])->name('upload.file');
Create a controller (FileUploadController
) to handle the file upload process:
php artisan make:controller FileUploadController
Open the generated controller (app/Http/Controllers/FileUploadController.php
) and implement the showUploadForm
and uploadFile
methods:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FileUploadController extends Controller
{
public function showUploadForm()
{
return view('upload');
}
public function uploadFile(Request $request)
{
$request->validate([
'file' => 'required|file|max:10240', // Max size in kilobytes (10MB)
]);
if ($request->file('file')->isValid()) {
$file = $request->file('file');
$filename = time() . '_' . $file->getClientOriginalName();
$file->storeAs('uploads', $filename); // Store file in storage/app/uploads directory
return redirect('/upload')->with('success', 'File uploaded successfully!');
}
return redirect('/upload')->with('error', 'File upload failed. Please try again.');
}
}
By default, Laravel stores uploaded files in the storage/app
directory. You can configure additional filesystems in the config/filesystems.php
configuration file.
Ensure that the storage/app/uploads
directory exists and is writable by the web server. You may need to create this directory manually:
mkdir -p storage/app/uploads
You can now test the file uploader by visiting the /upload
route in your browser and uploading a file using the form. The uploaded file should be stored in the storage/app/uploads
directory.
You can enhance the user experience by displaying success and error messages in the view (upload.blade.php
) to indicate whether the file upload was successful or not. You can access these messages using the session
helper or Laravel's with
method when redirecting.
That's it! You've successfully created a file uploader in Laravel. You can extend this functionality further by adding features such as file validation, file type restrictions, and integration with cloud storage services.