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