LARAVEL

Creating a custom error message


To create a custom error message for file validation in Laravel, you can specify the custom message using the messages() method within the validate() function. Here's how you can create a custom error message for file validation:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FileUploadController extends Controller
{
    public function showUploadForm()
    {
        return view('upload');
    }

  public function uploadFile(Request $request)
{
    $request->validate([
        'file' => 'required|file|mimes:jpg,jpeg,png,pdf|max:10240', // Max size in kilobytes (10MB)
    ], [
        'file.required' => 'Please select a file to upload.',
        'file.file' => 'The uploaded file is invalid.',
        'file.mimes' => 'Only JPG, JPEG, PNG, and PDF files are allowed.',
        'file.max' => 'The file size cannot exceed 10MB.',
    ]);

    if ($request->file('file')->isValid()) {
        $file = $request->file('file');
        $filename = time() . '_' . $file->getClientOriginalName();
        $file->storeAs('uploads', $filename); // Store file in storage/app/uploads directory

        return redirect('/upload')->with('success', 'File uploaded successfully!');
    }

    return redirect('/upload')->with('error', 'File upload failed. Please try again.');
}
}

Explanation:

  • In the validate() function, you can pass an array as the second argument to specify custom error messages for each validation rule.
  • Each key in the array corresponds to a field or validation rule, and the value is the custom error message you want to display.
  • In this example, we provided custom error messages for the 'file.required', 'file.file', 'file.mimes', and 'file.max' validation rules.

With these custom error messages, users will receive more informative feedback about why their file upload failed, helping them understand and correct any issues more easily.


LARAVEL