2

Is there any reason why we only have this static way to boot traits in Laravel:

static function bootMyTrait ()
{...}

Is there any way to boot trait and have model instance in the boot function? Like this:

function bootMyTrait ()
{
    if ($this instanceOf awesomeInterface)
    {
        $this->append('nice_attribute');
    }
}

I need this AF, and for a very long time haven't found any solution.

3

2 Answers 2

13

Since Laravel 5.7 you can use trait initializers, instead of trait booters. I've had the same task and was able to solve it like this:

public function initializeMyTrait()
{
    if ($this instanceOf awesomeInterface)
    {
        $this->append('nice_attribute');
    }
}
0

Well, no one seems to care :D

Good news, is that within 15 min, I've solved my problem with this in base model:

public function __construct(array $attributes = [])
{

    foreach (class_uses_recursive($this) as $trait)
    {
        if (method_exists($this, $method = 'init'.class_basename($trait))) {
            $this->{$method}();
        }
    }

    parent::__construct($attributes);
}

Edit

Instead of relying on traits for this, use Eloquent's accessors and mutators. For example, define the following methods on a User model:

// Any time `$user->first_name` is accessed, it will automatically Uppercase the first letter of $value
public function getFirstNameAttribute($value)
{
    return ucfirst($value);
}

This appends the $user->first_name attribute to the model. By prefixing the method name with get and suffixing it with Attribute you are telling Eloquent, Hey, this is an actual attribute on my model. It doesn't need to exist on the table.

On the other hand you can define a mutator:

// Any string set as first_name will automatically Uppercase words.
public function setFirstNameAttribute($value)
{
    $this->attributes['first_name'] = ucwords($value);
}

This will apply anything you do to $value before setting it in the $attributes array.

Of course, you can apply these to attributes that do exist on your database table. If you have raw, unformatted data, say a telephone number 1234567890, and you wanted to apply a country code, you could use an accessor method to mask the number without modifying the raw value from the database. And going the other way, if you wanted to apply a standard formatting to a value, you could use a mutator method so all your database values conform to a common standard.

Laravel Accessor and Mutators

6
  • I'm curious, what's the use case for needing it in a non static context?
    – user320487
    Commented Feb 2, 2018 at 16:06
  • @btl If you look at my question, you can see exact use case: appending attribute to eloquent. If you are not in Laravel too much, then in plain PHP use case may be adding necessary properties to object, or changing values of its properties (e.g. if some condition, like "implements Interface", is true). Now I want ask you - aren't these legit use cases? Am i doing something wrong and silly? Commented Feb 2, 2018 at 16:31
  • Yeah, you want to be using model accessors instead of what you're doing with the traits. I'll edit your answer with an example.
    – user320487
    Commented Feb 2, 2018 at 16:54
  • 2
    Take a peak at the answer now. Much easier and cleaner than using traits.
    – user320487
    Commented Feb 2, 2018 at 17:01
  • 1
    I really recommend against this practice. Laravel has created boot methods in traits to get the functionality of a constructor without having to use a constructor. Using constructors in traits will not scale too well.
    – Jed Lynch
    Commented Feb 10, 2021 at 23:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.