Using has() vs hasFile() in Laravel

1069
laravel-has-hasfile-request

In this article, we will learn about using has() vs hasFile() methods in laravel. These are very common methods when handling form requests in Laravel. Not knowing the differences between these two can sometimes give a lot of pain with debugging the code. So, this will be more of a tip than a tutorial.

The has() is used to check if a value is present in a request. It returns a boolean. So, if there are any input field in a request we need to check if a value exists or not, we use has() method. Thus, based on the returned result, we can handle the scenario.

<?php

..............
if ($request->has('email')) {
    //email has a value
}

On the other hand, hasFile()is used to check if the request has a file or not. Please note that checking a request with has()on the file input field will always return false. Thus, we need to check using hasFile() method. Also, we need to keep in mind that when we use a file in the request, we need to give enctype="multipart/form-data" in the form tag. An example is given below.

<?php

........
if ($request->hasFile('image')) {
    // file is present
}

Bonus:

Besides these methods, there are also several methods that can be handy when dealing with form requests. If we want to check if all the inputs are present at once, we can use the has() method with a list of the field names in an array.

<?php

............
if ($request->has(['name', 'email', 'phone'])) {
    // all the input fields are present
}

The above method checks if all field contains values whereas hasAny() will check if any of the specified input fields contains a value. In the example below, it will return true if any of the input fields i.e. name or email contains a value.

if ($request->hasAny(['name', 'email'])) {
    // either both or name or email has a value
}

Alternatively, we can also execute code only if a value is present in the form request. For this, we need to use whenHas() method. It can be hand and as well as clean instead of multiple if...else statements. The second parameter for this method is optional but if passed, it will be executed if the value is not present on the request.

<?php

..........
$request->whenHas('name', function ($input) {
    // value is present
});

// with callback function
$request->whenHas('name', function ($input) {
    // The "name" value is present...
}, function () {
    // The "name" value is not present...
});

There are many other methods which can be used according to our needs. All of the methods and their explanation can be found at this documentation.

Read More Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.