· 1 min read
Using casts in Laravel traits
Laravel doesn't merge a trait's $casts property into the model. Use an initializable trait and mergeCasts() instead.
- #laravel
- #php
- #eloquent
When working with Laravel, traits are a powerful way to reuse code across multiple models. However, when it comes to defining attribute casts within a trait, directly using the $casts is not going to work because it won’t merge by default.
To add $casts inside a trait, you’ll be using Initializable traits and mergeCasts. When you define a method named initialize{TraitName} in a trait, Laravel automatically calls it when the model is booted.
Here’s how you can do it:
trait HasTimestamps
{
protected function initializeHasTimestamps() {
$this->mergeCasts([
'created_at' => 'datetime',
'updated_at' => 'datetime',
]);
}
}
Now, when you use this trait in a model, the casts will be merged with the model’s existing casts:
class User extends Model {
use HasTimestamps;
protected $casts = [
'email_verified_at' => 'datetime',
];
}