0
0
LaravelHow-ToBeginner · 4 min read

How to Validate File Upload in Laravel: Simple Guide

In Laravel, you validate file uploads using the validate method on the request object with rules like file, 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 name. Common rules include:

  • required: file must be present
  • file: input must be a file
  • mimes:jpg,png,pdf: allowed file types
  • max:2048: max file size in kilobytes
php
request()->validate([
    'file_input_name' => 'required|file|mimes:jpg,png,pdf|max:2048',
]);
💻

Example

This example shows a controller method that validates an uploaded image file named photo. It requires the file, checks it is an image, limits types to jpeg and png, and restricts size to 1MB.

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UploadController extends Controller
{
    public function uploadPhoto(Request $request)
    {
        $validated = $request->validate([
            'photo' => 'required|file|image|mimes:jpeg,png|max:1024',
        ]);

        // If validation passes, store the file
        $path = $request->file('photo')->store('photos');

        return response()->json(['message' => 'File uploaded successfully', 'path' => $path]);
    }
}
Output
{"message":"File uploaded successfully","path":"photos/filename.jpg"}
⚠️

Common Pitfalls

Common mistakes include:

  • Forgetting the file rule, which can cause validation to pass even if the input is not a file.
  • Not specifying allowed mimes or mimetypes, leading to unexpected file types being accepted.
  • Setting max size too high or forgetting it, which can cause large files to upload and slow your app.
  • Not handling validation errors properly, which can confuse users.
php
<?php
// Wrong way: missing 'file' rule
$request->validate([
    'document' => 'required|mimes:pdf,docx|max:2048',
]);

// Right way: include 'file' rule
$request->validate([
    'document' => 'required|file|mimes:pdf,docx|max:2048',
]);
📊

Quick Reference

RuleDescriptionExample
requiredFile must be uploaded'photo' => 'required|file'
fileInput must be a file'document' => 'file'
mimesAllowed file extensions'image' => 'mimes:jpg,png,gif'
mimetypesAllowed MIME types'upload' => 'mimetypes:image/jpeg,image/png'
maxMax file size in KB'file' => 'max:2048'
imageFile must be an image'avatar' => 'image'

Key Takeaways

Always use the 'file' rule to ensure the input is a file.
Use 'mimes' or 'mimetypes' to restrict allowed file types.
Set 'max' to limit file size and protect your app.
Handle validation errors to give clear feedback to users.
Laravel's validate method makes file validation simple and secure.