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;
}
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',
];
Top comments (1)
Thanks!!!