File uploading is the most used functionality in web applications.
Lots of application allows the users to manipulate files to the server like – profile image, upload documents, import data, etc.
In this tutorial, I show how you can validate and upload a file in Laravel 7.
Contents
1. Controller
Create a new PagesController
controller.
php artisan make:controller PagesController
Here, create two methods –
- index – Load
index
view. - uploadFile – This method calls on
<form>
submit.
Define validation. I set the max upload file to 2 MB (2048 Kb). You can modify the file extensions and max upload size.
Read the submitted file with $request->file('file')
and assign to $file
.
Syntax –
$request->file([ file-element-name ]);
Assigned upload location "files"
to $location variable.
Execute $file->move($location,$filename);
to store the file.
The files
folder is created inside the public/
folder at the root from where you can access the uploaded files.
NOTE – Folder automatically created if it does not exist.
Completed Code
<?php namespace App\Http\Controllers; use Session; use Illuminate\Http\Request; class PagesController 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 = 'files'; // 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.
Here, define two routes –
- /
- uploadFile – Post type route which calls on
<form>
submit.
Completed Code
<?php Route::get('/', 'PagesController@index'); Route::post('/uploadFile', 'PagesController@uploadFile');
3. View
Create a new index.blade.php
file in resources/views/
directory.
Display SESSION message
variable value in <div>
if it is set.
Create a file element and a submit button in <form >
. Also, add {{ csrf_field() }}
inside <form>
.
Set <form >
action='/uploadFile'
and enctype='multipart/form-data'
.
Display error message in <span >
if the file is not validated.
Completed Code
<!DOCTYPE html> <html> <head> <title>How to upload a file in Laravel 7</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
In the example, I only used SESSION for displaying messages in the view file.
Modify the validation according to your requirement and you can find your files storage directory in public
folder.
You can view this tutorial to know file upload in Laravel 8.
If you found this tutorial helpful then don't forget to share.