Answer the question
In order to leave comments, you need to log in
Automatically set new property via setter?
How can I set a model setter in laravel so that it automatically sets a new collection value that is not in the database?
for example, I have an automatic property change through a getter :
I just set appends and a getter function in the model
protected $appends = ['created_at'];
public function getCreatedAtAttribute($value)
{
return Date::parse($value)->format('d F в H:i');
}
Answer the question
In order to leave comments, you need to log in
I’ll hint that it’s better not to get used to teaching the model to do what it can’t do, because it already carries crazy functionality in Laravel, but to write your own class in which to put the model as input and fill it with data from it in the constructor. And there this property can be made and other modules already rely on their class, which can do nothing but take and put. Because such a class without functionality can be left forever without any problems, because it will always perform the “give-take” task, unlike the Laravel model, which can do too much and refusing it will mean brainstorming and trying to close up the resulting holes with tape.
But if you really really want the model, then do it like this
protected $appends = ['created_at2'];
getCreatedAt2Attribute() {}
if you want it to be saved to the database, you need to write it to the array $this->attributes[ $name ] = $value; then call save();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question