DEV Community

loading...

Casting an Eloquent integer value to boolean

programmingdecoded profile image Philip Perry ・1 min read

I want to start to frequently post small things I'm learning through code reviews or simply googling for a solution.

Here's a nice solution that once again surprised me about Laravel's feature richness.

I wanted to return a value that gets saved as an integer in the 'active' column in a database table as a boolean.

My initial ugly solution was to change the attribute like this (that is to force the return type to boolean):

public function getActiveAttribute($value): bool
{
       return $value;
}
Enter fullscreen mode Exit fullscreen mode

My code reviewer found a much better solution:

https://laravel.com/docs/6.x/eloquent-mutators#attribute-casting

So I replaced above code in the Eloquent model with this:

 protected $casts = [
        'active' => 'boolean',
    ];
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

pic
Editor guide
Collapse
makhosi6 profile image
makhosi6

Thanks!!!