2 ways to Check if Request has File in Laravel – Quick Answer

January 10, 2023
Laravel
2 ways to Check if Request has File in Laravel – Quick Answer

In this tutorial, you will learn how to check if the request has file in laravel.

In the controller sometimes we need to know whether there is file or not, so we can display an error message in view.

We will be discussing 2 ways of checking if the request has file in laravel or not.

Let’s get started!

Method 1: Check If Request Has File Using hasFile

To check if the request has file in laravel, we can use hasFile method in Illuminate\Http\Request. Here is how you do it in the controller:

use Illuminate\Http\Request;

public function my_function(Request $request)
{
    if ($request->hasFile('file')) {
       //add the code here which you want to execute if file is found
    } else {
      //add the code here which you want to execute if file is not found
    }
}

In the above code, we have used hasFile, a method of Illuminate\Http\Request in which we are passing the field name as the argument, which is file in our case.

Method 2: Check If Request Has File Using has

Similar to hasFile, you can use also used has, this works similarly to hasFile but generally used to validate the field’s name.

Here is how you do in the controller:

use Illuminate\Http\Request;

public function my_function(Request $request)
{
    if ($request->has('file')) {
       //add the code here which you want to execute if file is found
    } else {
      //add the code here which you want to execute if file is not found
    }
}

Conclusion

Hope you have learned in the above article 2 ways to check if a Request has file in laravel or not using hasfile and has methods.

See you in the next one!

Tags

Write a Reply or Comment

Your email address will not be published. Required fields are marked *


Icon