How to upload a file in Laravel 8

With file upload, a user can import file data to the database, upload media files, etc.

In this tutorial, I show how you can upload a file and add validation in the Laravel 8 project.

How to upload a file in Laravel 8


Contents

  1. Controller
  2. Route
  3. View
  4. Output
  5. Conclusion

1. Controller

Create a PageController controller.

php artisan make:controller PageController

Create 2 methods –

  • index() – Load index view.
  • uploadFile() – This method is used to upload the file.

Define file validation. I set the max upload file size to 2 MB (2048 KB).

If successfully validated then assign the file name to $filename and upload location "files" to the $location variable.

Execute $file->move($location,$filename); to store the file.

Use SESSION flash to store upload status and class name.

Redirect to "/".

Completed Code

<?php

namespace App\Http\Controllers;

use Session;
use Illuminate\Http\Request;

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 = '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.
  • Define 2 routes –
    • / – Load index view.
    • /uploadFile – This use to upload a file.

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. 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.

Display error in <span > if not validated.

Completed Code

<!DOCTYPE html>
<html>
<head>
  <title>How to upload a file in Laravel 8</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

View 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 view this tutorial to know jQuery AJAX file upload in Laravel 8.

If you found this tutorial helpful then don't forget to share.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.

Leave a Comment