File sharing has become a crucial aspect of life in the modern digital age, and many websites now allow users to share files. However, file uploading can also be a security concern if done incorrectly. Thus, it is essential to have a solid file validation system in place to ensure that the uploaded files meet specific requirements and do not contain any malicious content.
Laravel already has built-in file upload with validation functionality.
In this tutorial, I show how you can upload a file with validation in the Laravel 10 project.
Table of Contents
- Create the Controller & Add Upload file Logic
- Set Up the Route
- View – Create the File Upload Form
- Output
- Conclusion
1. Create the Controller & Add Upload file Logic
- Create a
PageController
controller by executing the following command:
php artisan make:controller PageController
- Open
app/Http/Controllers/PageController.php
file. - Import the
Session
class at the top of the file. This will allow you to use it for displaying the upload status message. - Create 2 methods –
- index() – This method loads the
index
view. - uploadFile() – This method is responsible for uploading the file.
- index() – This method loads the
- Define file validation rules to specify the allowed file extensions, including
png
,jpg
,jpeg
,csv
,txt
, andpdf
. Additionally, set the maximum upload file size to 2 MB (2048 KB). - If the uploaded file fails validation, redirect back to the previous page with an error message using the
Session
flash. If the file is validated successfully, assign the file name to the$filename
variable and the upload location to the$location
variable. - Execute the
$file->move($location, $filename)
method to upload the file. Pass the upload location and the file name with the extension as arguments. - Store the success message in the
SESSION
flash data to display it on the page. Store the class name and message in the flash data. - Redirect to
"/"
.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Session; class PageController extends Controller { public function index(){ return view('index'); } public function uploadFile(Request $request){ // Validation $request->validate([ 'file' => 'required|mimes:png,jpg,jpeg,csv,txt,pdf|max:2048' ]); if($request->file('file')) { $file = $request->file('file'); $filename = time().'_'.$file->getClientOriginalName(); // File upload location $location = 'uploads'; // Upload file $file->move($location,$filename); Session::flash('message','Upload Successfully.'); Session::flash('alert-class', 'alert-success'); }else{ Session::flash('message','File not uploaded.'); Session::flash('alert-class', 'alert-danger'); } return redirect('/'); } }
2. Set Up the Route
- Open
routes/web.php
file. - Here, define 2 routes –
- / – Defined as a GET route that loads the index view.
- /uploadFile – Defined as a POST route. This route is used for file uploads.
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\PageController; Route::get('/', [PageController::class, 'index']); Route::post('/uploadFile', [PageController::class, 'uploadFile'])->name('uploadFile');
3. View – Create the File Upload Form
- Create a file named
index.blade.php
inside theresources/views/
folder. - If the
message
session exists, display a Bootstrap alert message with the corresponding content. Use thealert-class
session to set the appropriate alert class. - Create a
<form>
element with the following attributes:action="{{ route('uploadFile') }}"
,enctype='multipart/form-data'
, andmethod="post"
. This form will be used to upload files. - Inside the
<form>
element, add a file input element and a submit button. The file input element allows users to select a file to upload, while the submit button triggers the upload process. - To show an error message if the selected file fails validation, include a
<span>
element with the classerrormsg text-danger
and the content{{ $errors->first('file') }}
.
<!DOCTYPE html> <html> <head> <title>How to upload a file with validation in Laravel 10</title> <!-- Meta --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> </head> <body> <div class="container"> <div class="row"> <div class="col-md-12 col-sm-12 col-xs-12"> <!-- Alert message (start) --> @if(Session::has('message')) <div class="alert {{ Session::get('alert-class') }}"> {{ Session::get('message') }} </div> @endif <!-- Alert message (end) --> <form action="{{route('uploadFile')}}" enctype='multipart/form-data' method="post" > {{csrf_field()}} <div class="form-group"> <label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">File <span class="required">*</span></label> <div class="col-md-6 col-sm-6 col-xs-12"> <input type='file' name='file' class="form-control"> @if ($errors->has('file')) <span class="errormsg text-danger">{{ $errors->first('file') }}</span> @endif </div> </div> <div class="form-group"> <div class="col-md-6"> <input type="submit" name="submit" value='Submit' class='btn btn-success'> </div> </div> </form> </div> </div> </div> </body> </html>
4. Output
5. Conclusion
Modify the validation rules in the controller to match your specific requirements. Update the validation rules based on the file extensions you want to allow and the maximum file size. Customize the validation logic to suit your needs.
Specify the desired upload location by assigning it to the $location
variable. If the specified folder does not exist, create it programmatically before uploading the file. This ensures that the upload location is available and accessible.
If you allow users to upload large files then ensure that you check the upload_max_filesize
and post_max_size
values in the php.ini
file. Update these values if necessary to accommodate larger file uploads.
The provided code can be utilized in Laravel 9 or 8 without any issues.
If you are interested in learning about jQuery AJAX file upload in Laravel 10, you can refer to the tutorial mentioned: Tutorial: How to upload a file using jQuery AJAX in Laravel 10
If you found this tutorial helpful then don't forget to share.