Convert request parameters to boolean in Laravel
Sometimes, you might want to convert some of the request parameters to boolean. For instance, take a checkbox field. Unless and until, it hasn’t been checked it won’t be passed through to the request. In such a case, it would be beneficial to convert such inputs to boolean.
Laravel 6.x has such a helper utility method in Illuminate\Http\Request
called boolean($key)
which takes the input name as a $key
and returns an equivalent boolean value for the same. It does so by taking input using the input()
method and filters it through filter_var and FILTER_VALIDATE_BOOLEAN
.
Here are some examples on how you can use this.
// checkbox
Request::boolean('available_for_hire');
// true if checked
// false if not checked
// string - Yes/No
Request::boolean('is_active');
// true for 'Yes'
// false for 'No'
Here, available_for_hire
might be an checkbox field or a string input, passing it through the boolean()
will return a boolean value based on the FILTER_VALIDATE_BOOLEAN
varible filter.
The method set the default to be false
so then an undefined variable (eg unchecked checkbox) would act as false. i.e If the key is not found in the request input, false
is returned.
But that’s also customizable. So, if you want a field’s default value to be true
when it’s undefined, here’s how you can do it.
Request::boolean('is_active', true);
Here’s how the boolean()
method looks like behind the scene.
/**
* Retrieve input as a boolean value.
*
* @param string|null $key
* @param bool $default
* @return bool
*/
public function boolean($key = null, $default = false)
{
return filter_var(
$this->input($key, $default),
FILTER_VALIDATE_BOOLEAN
);
}
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.