PHP

Boolean field validation in Laravel

In Laravel, we can write validation rules in custom classes to validate form fields. These classes are extends from FormRequest.

Sometimes, you can get a Boolean field value as string like ‘true’ or ‘false’ or ‘on’, as value can be as string and got error as following.

The {fieldname} field must be true or false

Laravel Documentation

It’s mentioned that Boolean field will accept input as true, false, 1, 0, “1”, and “0”.

Following is the Request class example with Boolean field.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ProductRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */    public function rules()
    {
        return [
            'is_active'=>'boolean|required',
        ];
    }
}

For instance, I am using just one input fields is_active, which is Boolean and also required.

Now with the above class, when you will get request with is_active as ‘true’ or ‘false’, you will get error “The is_active field must be true or false”.

You can get this situation when you are sending values to API from Postman  or Swagger UI or sending values from form in double or single quotes or some browsers used to send ‘on’ for radio buttons or checkboxes.

To handle this we have two solutions, one with prepareForValidation  method and other one is with writing custom rule. Right now I am giving you example with prepareForValidation method.

You will need to add method prepareForValidation in your Request class as following.

     /**
     * Prepare inputs for validation.
     *
     * @return void
     */    protected function prepareForValidation()
    {
        $this->merge([
            'is_active' => $this->toBoolean($this->is_active),
        ]);
    }

    /**
     * Convert to boolean
     *
     * @param $booleable
     * @return boolean
     */    private function toBoolean($booleable)
    {
        return filter_var($booleable, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
    }

FILTER_VALIDATE_BOOLEAN will identify value like ‘true’, ‘false’, ‘yes’, ‘no’, ‘on’, ‘off’ and it’s not case-sensitive while validating input value.

FILTER_VALIDATE_BOOLEAN will return true if input value is ‘true’, ‘on’, ‘yes’, or ‘1’.

When FILTER_NULL_ON_FAILURE flag is set then it will return false for ‘false’, ‘off’, ‘0’, or ‘no’ and null for non-boolean values.

Final code for request class will be as following.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ProductRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */    public function rules()
    {
        return [
            'is_active'=>'boolean|required',
        ];
    }

    /**
     * Prepare inputs for validation.
     *
     * @return void
     */    protected function prepareForValidation()
    {
        $this->merge([
            'is_active' => $this->toBoolean($this->is_active),
        ]);
    }

    /**
     * Convert to boolean
     *
     * @param $booleable
     * @return boolean
     */    private function toBoolean($booleable)
    {
        return filter_var($booleable, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
    }
}

Hope this will help someone.

websourceblog

ReactJs, NodeJs, Amazon Web Services, Symfony, Laravel, CodeIgniter, Zend Framework, WordPress, Drupal, Magento, Angular

Recent Posts

How to reset WSL 2 user’s password?

You can easily reset WSL 2 users' password, by just following the following steps. Open…

2 months ago

DreamHost Web Hosting

DreamHost a web hosting company, founded in 1997. It is offering sort of hosting services,…

10 months ago

How to add submenu or menu in any specific menu option in WordPress programmatically?

Menus in WordPress are highly versatile and can be easily modified to change in your…

11 months ago

Laravel 8 error target class controller does not exist.

Laravel is famous and robust PHP framework, widely used in different type of projects. While…

1 year ago

Define Private Methods/Functions in Python Class.

Python is very powerful and famous language, which allow us to write code as per…

2 years ago

Working with dates in PHP.

In this article, I am going to show you how we can get specific dates…

2 years ago