To allow both lower and upper case file extensions and MIME types during file upload in Laravel, you can create a custom validation rule. Here's a step-by-step solution:
-
Create a Custom Validation Rule:
First, generate a custom validation rule using the Artisan command:
php artisan make:rule FileExtension -
Implement the Custom Validation Logic:
Open the generated
FileExtensionrule class located inapp/Rules/FileExtension.phpand implement the logic to check for both lower and upper case file extensions and MIME types.<?php namespace App\Rules; use Illuminate\Contracts\Validation\Rule; class FileExtension implements Rule { protected $allowedExtensions; public function __construct(array $allowedExtensions) { $this->allowedExtensions = $allowedExtensions; } public function passes($attribute, $value) { $extension = strtolower($value->getClientOriginalExtension()); return in_array($extension, array_map('strtolower', $this->allowedExtensions)); } public function message() { return 'The :attribute must be a file of type: ' . implode(', ', $this->allowedExtensions) . '.'; } } -
Use the Custom Validation Rule in Your Controller:
In your controller, use the custom validation rule when validating the file upload.
use App\Rules\FileExtension; use Illuminate\Http\Request; class FileUploadController extends Controller { public function upload(Request $request) { $request->validate([ 'file' => ['required', 'file', new FileExtension(['jpg', 'jpeg', 'png', 'pdf'])], ]); // Handle the file upload $file = $request->file('file'); $path = $file->store('uploads'); return response()->json(['path' => $path], 200); } } -
Update Your Routes:
Ensure you have a route that points to your file upload controller method.
use App\Http\Controllers\FileUploadController; Route::post('/upload', [FileUploadController::class, 'upload']);
This solution ensures that the file extension is validated in a case-insensitive manner, allowing both lower and upper case file extensions. The custom validation rule checks the file extension against a list of allowed extensions, converting both the file extension and the allowed extensions to lowercase for comparison.