Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

it-is-all-about-laravel's avatar

request validation rule json

hey everyone, I'm attemping to use the json validation rule to validate a request parameter of a json data type https://laravel.com/docs/6.x/validation#rule-json

i'm having a problem where laravel always reports the value as invalid json. here is an example of the json i am submitting, which is valid json according to https://jsonformatter.org/

{
  "detail": {
        "id": "1",
        "firstName": "Tom",
        "lastName": "Cruise",
        "photo": "https://jsonformatter.org/img/tom-cruise.jpg"
  }
}

and my validation rules

$validatedData = $request->validate([
        'detail' => 'required|json',
    ]);

I ran some debugging and found it seems to fail here;

// Illuminate/Validation/Concerns/ValidatesAttributes.php#L1134
    public function validateJson($attribute, $value)
    {
        if (! is_scalar($value) && ! method_exists($value, '__toString')) {
            return false;
        }
        json_decode($value);
        return json_last_error() === JSON_ERROR_NONE;
    }

It is failing because ! is_scalar($value) returns true - i.e. returns that the $value being validated is a scalar.

The php documentation for is_scalar https://www.php.net/manual/en/function.is-scalar.php states that an array is not a scalar and therefore I expected ! is_scalar($value) should return a value of false because the $value passed to this function (that was originally json in my request) has already been converted to an associative array by laravel.

When debugging I ran $value through is_array() and that returned true. So PHP recognises it as an array yet also recognises the same array is a scalar - despite the is_scalar documentation saying it should not recognise an array as scalar.

What are your thoughts? Do you agree this does not make sense, can you replicate this same issue of a PHP array testing as true in is_scalar()? Have you been able to validate a request attribute using the json validation rule?

Thanks

0 likes
1 reply
jlrdw's avatar
$this->validate($request->detail, [
    'firstName' => 'required|digits:5',
    // etc
    ]);

Just typed out but something like that.

Please or to participate in this conversation.