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.
Contents
1. Create Controller
- Create a
PageController
controller.
php artisan make:controller PageController
- Open
app/Http/Controllers/PageController.php
file. - Include
Session
. I am using this only for displaying the upload status message.
Create 2 methods –
- index() – Load
index
view. - uploadFile() – This method is used to upload the file.
Define file validation. Specified allowed file extensions – png, jpg, jpeg, csv, txt, pdf
and I set the max upload file size to 2 MB (2048 KB).
Page redirects with error messages if file is not validated. If validated then assign the file name to $filename
and upload location uploads
to the $location
variable.
Execute $file->move($location,$filename);
to upload a file. Here, pass the upload location and file name with the extension.
Store success message to SESSION flash to display it on the page. In the SESSION flash store the class name and message.
Redirect to "/"
.
Completed Code
<?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. Route
- Open
routes/web.php
file. - Define 2 routes –
- / – Load index view.
- /uploadFile – This is use for file upload.
Completed Code
<?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. Create View
Create index.blade.php
file in resources/views/
.
Display bootstrap alert message if 'message'
 Session exists. Also, set alert class using 'alert-class'
 Session.
Create <form action="{{route('uploadFile')}}" enctype='multipart/form-data' method="post" >
.
In the <form >
create a file element and a submit button. Using <span class="errormsg text-danger">{{ $errors->first('file') }}</span>
to display an error message if the selected file is not validated.
Completed Code
<!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 according to your requirement in the controller. Specify upload location in $location
variable. Folder created while uploading if not exists.
If you are allowing to upload large files then make sure to check upload_max_filesize
and post_max_size
values in the php.ini file and update it if required.
You can use to same code if you are on Laravel 9 or 8.
You can view this tutorial to know jQuery AJAX file upload in Laravel 10.
If you found this tutorial helpful then don't forget to share.