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

leon@codecat.com.au's avatar

Boolean field in json post failing validation

Hey,

I have a Laravel API and I'm trying to post to an endpoint from a JS frontend app.

The endpoint has a field that takes a boolean, However when I try and pass it as true the laravel validation fails. If I pass the value as 1 instead of true it works fine.

I've tried attribute casting and attribute mutating, neither fixes the issue. Also I'm definitely passing the boolean true and not the string 'true'.

I found this old github ticket from ages ago that's been closed...seems to have been the same problem: https://github.com/laravel/framework/issues/4067

Anyone have any ideas? or can confirm this is a bug?

Cheers

0 likes
2 replies
leon@codecat.com.au's avatar
Level 2

Managed to work out a solution based on this stack overflow post: http://stackoverflow.com/questions/28854585/laravel-5-form-request-data-pre-manipulation#answer-32038527

It does seem like a Laravel bug to me though, really this should work out of the box.

Anyway for anyone who comes across this, my solution is:

Place the following in your form request and replace the $boolean array with all the booleans you are validating.

/**
     * Extend the default getValidatorInstance method
     * so fields can be modified or added before validation
     *
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function getValidatorInstance()
    {
        $booleans = ['aBoolean', 'anotherBoolean'];
        $data = $this->all();

        foreach ($booleans as $boolean) {
            if(array_key_exists($boolean, $data))
                $data[$boolean] = (boolean) $data[$boolean];
        }

        $this->getInputSource()->replace($data);

        return parent::getValidatorInstance();

    }
1 like
SteveEdson's avatar

Thanks, stumbled on this issue. I had to change the line to this though

$data[$boolean] = filter_var($data[$boolean], FILTER_VALIDATE_BOOLEAN);

otherwise "false" was being resolved to true

Please or to participate in this conversation.