DEV Community

Philip Perry
Philip Perry

Posted on

Casting an Eloquent integer value to boolean

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

Top comments (1)

Collapse
 
makhosii profile image
makhosii

Thanks!!!