Summer sale! Save 50% on access to our entire library of courses.Join here →

How to Use Casts Inside a Laravel Trait

May 21st, 2024

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.

Thanks for reading! If you found this article helpful, you might enjoy our practical screencasts too.
Author
Alex Garrett-Smith
Share :

Comments

No comments, yet. Be the first to leave a comment.

Tagged under