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

nikocraft's avatar

casting to boolean

I have this:

    protected $casts = [
        'published' => 'boolean',
    ];

However when I do this:

{{$post->published}}

it prints 1 instead of true. Am I doing something wrong? I followed the docs: https://laravel.com/docs/5.3/eloquent-mutators#attribute-casting

0 likes
8 replies
tomopongrac's avatar

From the manual

http://php.net/manual/en/language.types.string.php

A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.

You can do this

echo $bool_val ? 'true' : 'false';
1 like
InaniELHoussain's avatar

or in your model

public function getPublishedAttribute($value)
    {
    if($value =="") return false;
    return true;
    }
richardh's avatar

I had to add this as well

       $value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
2 likes
rawilk's avatar

@nikocraft - No, you don't need to do that. What @tomopongrac said is really what you need. It's a lot simpler to just cast it in your model and do this: {{ $post->published ? 'true' : 'false' }}.

pilat's avatar

I'm afraid it's confusing and may lead to errors. Here's the documentation:

Now the is_admin attribute will always be cast to a boolean when you access it, even if the underlying value is stored in the database as an integer:

Ok, so I can check it like this: $user->is_admin === true?

nope.

# tinker

>>> App\Activity::first()->processed === 0
=> true

>>> App\Activity::first()->processed === false
=> false
rawilk's avatar

@pilat - Did you even cast it on your model? I've always been able to do something like $user->is_admin === true when using $casts on the model.

pilat's avatar

@WILK_RANDALL - My bad, checked on wrong model… Yes, it passes strict comparison, which is exactly what's expected :-)

Please or to participate in this conversation.