laraveleloquentmodelmutators

Repeat Mutators


I'm using several mutators that are basically the same on different models and within the same models, for different fields. eg: to tidy dates:

    public function getStartShortDateAttribute()
    {
        return $this->start_time->format('d-m-y');
    }

Is there a standard way to reuse the same mutator for several fields across models?


Solution

  • Use a trait, which is a way to reuse code across classes.

    trait HasStartTimes {
        public function getStartShortDateAttribute()
        {
            return $this->start_time->format('d-m-y');
        }
    }
    

    Now you can use this trait in your class, with the use statement. When done it will include the traits function, in the classes that uses the trait. This is an design approach that is used already in Laravel, see AuthenticatesUsers.

    class YourModel {
        use HasStartTimes;
    }