baskarks's avatar

custom validation to allow both lower and upper case file extension

while upload allow both lower and upper case file extension and mime types

0 likes
1 reply
LaryAI's avatar
Level 58

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:

  1. Create a Custom Validation Rule:

    First, generate a custom validation rule using the Artisan command:

    php artisan make:rule FileExtension
    
  2. Implement the Custom Validation Logic:

    Open the generated FileExtension rule class located in app/Rules/FileExtension.php and 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) . '.';
        }
    }
    
  3. 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);
        }
    }
    
  4. 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.

Please or to participate in this conversation.