Laravel 11 File Upload Example Tutorial
In this tutorial, we will explore how to handle file uploads in a Laravel 11 application. This guide covers everything from setting up the project to handling the file upload process and storing the uploaded files. We’ll also show how to display the uploaded files.
We will create two routes: one for rendering the form using a GET request and another for handling the file upload using a POST request. The uploaded file will be stored in the uploads
directory within the public folder. Follow these steps to implement file uploads in your Laravel 11 application.
Step 1 : Install Laravel 11
First, ensure you have Laravel installed. If not, you can create a new Laravel application using the following command :
composer create-project laravel/laravel example-app
Step 2 : Create a Controller
Next, we will create a FileController
to handle the file upload logic. This controller will have two methods: index
to render the upload form and store
to handle the file upload.
Create the controller using the artisan command:
php artisan make:controller FileController
Now, update the FileController
with the following code :
validate([
'file' => 'required|mimes:pdf,xlsx,csv|max:2048',
]);
$fileName = time().'.'.$request->file->extension();
$request->file->move(public_path('uploads'), $fileName);
/*
Write Code Here for
Store $fileName in DATABASE
*/
return back()
->with('success', 'You have successfully uploaded the file.')
->with('file', $fileName);
}
}
Step 3 : Create and Add Routes
Now, we need to create routes to display the form and handle the file upload. Open the routes/web.php
file and add the following routes:
name('file.store');
Step 3 : Create and Add Routes
Now, we need to create routes to display the form and handle the file upload. Open the routes/web.php
file and add the following routes:
name('file.store');
Step 4 : Create the Blade File
Create a Blade view to display the file upload form.
In the resources/views
directory, create a new file named fileUpload.blade.php
and add the following code :
Laravel 11 File Upload Example
Laravel 11 File Upload Example
@if ($message = Session::get('success'))
{{ $message }}
@endif
Step 5 : Run the Laravel Application
Finally, run your Laravel application using the following command :
php artisan serve
Open your browser and navigate to http://localhost:8000/file-upload
. You should see the file upload form. Select a file and click “Upload” to test the file upload functionality.
Conclusion :
This tutorial walked you through the steps to handle file uploads in a Laravel 11 application. We covered setting up the project, creating a controller, adding routes, and creating a Blade view for the upload form. By following these steps, you can implement file uploads in your Laravel application and handle file storage efficiently.