Convert request parameters to boolean in Laravel

Amit Merchant · February 16, 2020 ·

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
     );
}
Learn the fundamentals of PHP 8 (and 8.1), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-read guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?