How to Add File Type Validation

AuthorSumit Dey Sarkar

Pubish Date25 Mar 2023

categoryLaravel

In this tutorial we will learn how to add file type validation in laravel.

 

How to Add File Type Validation

In Laravel, you can easily add file type validation by using the built-in validation rules. Here's an example of how to add file type validation for a file input field:

 

1) In your Laravel project, open the controller where you want to add file type validation.

 

2) Add the following validation rule to your validation rules array:

'file_input_name' => 'required|mimes:jpeg,png,pdf'

Note: Replace "file_input_name" with the name of your file input field, and add any additional file types that you want to allow.

 

3) In your view file, add the following code to the form element that contains the file input field:

enctype="multipart/form-data"

This code is required to enable file uploads in your form.

 

4) In your controller method, use the following code to check if the file type is valid:

if ($request->file('file_input_name')->isValid()) {
    // File is valid, continue with processing
} else {
    // File is invalid, redirect back with error message
    return redirect()->back()->withErrors(['msg', 'File type is invalid']);
}

Note: Replace "file_input_name" with the name of your file input field.

 

That's it! Now your Laravel project will validate the file type of the uploaded file and display an error message if the file type is not allowed.

Comments 0

Leave a comment