Save 50% in the Black Friday sale
Ends inJoin here

How to Use Casts Inside a Laravel Trait

May 21st, 2024 • 1 minute read time

If you move over some functionality to a trait in Laravel that requires casts to be added as part of the trait's functionality, this won't merge by default.

To add to $casts inside a trait, you'll first need to implement the initialize prefix to the current name of the trait. Here's an example with an Archivable trait I recently implemented in a course.

trait Archivable
{
    public function initializeArchivable()
    {
        //
    }
}

This method is invoked before anything else happens within your model's setup, so it's the perfect time to merge in any additional casts your trait needs to add to the model it's being applied to.

To do that, simply use the mergeCasts method.

trait Archivable
{
    public function initializeArchivable()
    {
        $this->mergeCasts([
            'archived_at' => 'datetime'
        ]);
    }
}

And that's it. Your casts will be applied to the model, and any casts already defined will stay put.

If you found this article helpful, you'll love our practical screencasts.
Author
Alex Garrett-Smith
Share :

Comments

No comments, yet. Be the first!

Tagged under