laravellaravel-8laravel-validation

Laravel Integer Validation without quotes


Using Laravel 8, in a JSON POST request I have a field { "is_active": "1"} in string quotes. Have the below validation in Laravel

'is_active' => ['required','integer',Rule::in([0, 1]) ]

It's accepting integer 1 even enclosed in quotes. How to do strict check so that it allows only { "is_active": 1}


Solution

  • Type casting converts the value to a chosen type by writing the type within parentheses before the value to convert. The casts allowed are: (int) - cast to int.

    https://laravel.com/docs/8.x/eloquent-mutators#cast-parameters

    e.g

    We have a property of a model called cast in which you can specify your column names just like below:

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'rating' => 'integer',
    ];