0
0
LaravelHow-ToBeginner · 3 min read

How to Validate File Uploads in Laravel Easily

In Laravel, you validate files using the validate method on the request object with rules like file, image, mimes, and max. This ensures the uploaded file meets your requirements before processing it.
📐

Syntax

Use the validate method on the request object with an array of rules for the file input. Common rules include:

  • file: Ensures the input is a file.
  • image: Ensures the file is an image.
  • mimes:types: Restricts file types by extension (e.g., mimes:jpg,png,pdf).
  • max:size: Limits file size in kilobytes.
php
request()->validate([
    'file_input_name' => 'required|file|mimes:jpg,png,pdf|max:2048'
]);
💻

Example

This example shows how to validate an uploaded file named document to be a required PDF file no larger than 2MB.

php
<?php

use Illuminate\Http\Request;

Route::post('/upload', function (Request $request) {
    $validated = $request->validate([
        'document' => 'required|file|mimes:pdf|max:2048',
    ]);

    // If validation passes, you can store the file
    $path = $request->file('document')->store('documents');

    return 'File uploaded successfully to ' . $path;
});
Output
File uploaded successfully to documents/filename.pdf
⚠️

Common Pitfalls

Common mistakes when validating files in Laravel include:

  • Forgetting to include file or image rule, which can cause validation to pass incorrectly.
  • Using mimetypes instead of mimes when you want to check file extensions.
  • Not setting the enctype="multipart/form-data" attribute on the HTML form, which prevents file uploads.
  • Setting max size too low or forgetting it, leading to unexpected upload failures.
php
/* Wrong way: missing 'file' rule */
$request->validate([
    'photo' => 'required|mimes:jpg,png'
]);

/* Right way: include 'file' rule */
$request->validate([
    'photo' => 'required|file|mimes:jpg,png'
]);
📊

Quick Reference

RuleDescriptionExample
fileEnsures the input is a file upload'file'
imageEnsures the file is an image (jpeg, png, bmp, gif, svg, or webp)'image'
mimes:typesRestricts file extensions'mimes:jpg,png,pdf'
mimetypes:typesRestricts MIME types'mimetypes:application/pdf,image/jpeg'
max:sizeLimits file size in kilobytes'max:2048' (2MB)
requiredFile must be present'required'

Key Takeaways

Always use the 'file' or 'image' rule to validate file inputs in Laravel.
Use 'mimes' to restrict allowed file extensions and 'max' to limit file size.
Set your HTML form's enctype to 'multipart/form-data' to enable file uploads.
Laravel's validate method automatically stops and returns errors if validation fails.
Check validation rules carefully to avoid common mistakes like missing 'file' rule.