How to validate file in Laravel in 3 Steps – Upload File Validation Laravel

Today, I will explain to you how to validate a file in Laravel using a code example for your Laravel project. Creating a functionality which uploads a file is a very easy task for any web developer.

Millions of photos, videos and documents are uploaded daily to various websites. It is very easy to use the Laravel Validation for handling file in this example. So simply follow my step-by-step instructions and learn how to use Laravel Validation file Example.

More Laravel Code Examples Here

So let’s start with an example and follow my steps to validate a file upload in Laravel.

Solution

$request->validate([
  'file' => 'required|mimes:png,jpg,jpeg,csv,txt,xlx,xls,pdf|max:2048'
]);

Below Example to implement the Solutioni :


Step 1: Create Route


To create a route in web.php, use the following code.


Route :routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UploadController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('upload/file', [UploadController::class, 'index']);
Route::post('upload/file/data', [UploadController::class, 'uploadFile'])->name('upload.file');


Step 2: Create a fileUploadController Controller


Next we will need a controller which will handle file validation for us. Lets create a controller in Laravel and name it fileUploadController. We will create a controller in Laravel using the following command.

We need to open a command prompt and point it to the root directory of our Laravel installation. There we can use the following command to create a controller.

php artisan make:controller fileUploadController

Controller : app/Http/Controllers/UploadController.php

Step 3: Adding File Validation function in fileUploadController

Now we need to use the following code in our controller which we created in Step 2

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Validator;

class UploadController extends Controller
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function index(){
      return view('uploadFile');
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    public function uploadFile(Request $request){
        $request->validate([
        'file' => 'required|mimes:png,jpg,jpeg,csv,txt,xlx,xls,pdf|max:2048'
        ]);

        $file = new File;

        if($request->file()) {
            $name = time().'_'.$request->file->getClientOriginalName();
            $filePath = $request->file('file')->storeAs('uploads', $name, 'public');

            $file->name = time().'_'.$request->file->getClientOriginalName();
            $file->file = '/storage/' . $filePath;
            $file->save();

            return back()
            ->with('success','File has uploaded to the database.')
            ->with('file', $name);
        }
     }
}

Step 4: Create a UploadFile Blade File


Next you can require to the uploadFile.blade.php so create a uploadFile.blade.php in just following step.

View :resources/views/uploadFile.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

    <title>Laravel Validation File Example</title>
    <style>
        .container {
            max-width: 450px;
        }
        dl, ol, ul {
            margin: 0;
            padding: 0;
            list-style: none;
        }
    </style>
</head>

<body>
    <div class="container mt-5">
      <div class="card" style="width: 25rem;">
        <h5 class="card-title text-center mt-3">Laravel Validation File Example</h5>
        <div class="card-body">
          
            <form action="{{route('upload.file')}}" method="post" enctype="multipart/form-data">
                @csrf
                @if ($msg = Session::get('success'))
                <div class="alert alert-success">
                    <strong>{{ $msg }}</strong>
                </div>
              @endif

              @if (count($errors) > 0)
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                          <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
              @endif

                <div class="custom-file">
                    <input type="file" name="file" class="custom-file-input" id="chooseFile">
                    <label class="custom-file-label" for="chooseFile">Choose file</label>
                </div>

                <button type="submit" name="submit" class="btn btn-primary btn-block mt-4">
                    Upload Files
                </button>
            </form>
        </div>
    </div>
  </div>

</body>
</html>

So, finally we are done with our code we can get below output.