@twg_ The easier way is to use a Mutator on Eloquent model: https://laravel.com/docs/8.x/eloquent-mutators#defining-a-mutator
Manipulate data before it's saved by resource
I have a field called 'Title' and I need to lowercase it and then hyphenate it before saving it. I know I can call the static::creatting on the model boot. Just not sure how to get the value that I'ma bout to save to modify it.
protected static function booted()
{
static::creating(function ($model) {
// dd($model->toArray()); // uncomment this line to see that you get the model as an argument
$model->title = mb_strtolower($model->title);
});
}
@twg_ This should work if you want to change it to lowercase when saving using the creating event as you suggested yourself.
@amaury is also correct that an mutator might be a better choice here, then you will convert it to lowercase directly when the title is set.
https://laravel.com/docs/8.x/eloquent-mutators#defining-a-mutator
A mutator have the benefit of doing the change directly, look at these examples to see the difference in behaviour between using the creating event and a mutator.
// using the creating event:
$model->title = 'HELLO';
dd($model->title); // will output HELLO unchanged if not saved
// using a mutator
$model->title = 'HELLO';
dd($model->title); // will output hello even if not saved yet
The mutator would look something like this:
public function setTitleAttribute($value)
{
$this->attributes['title'] = mb_strtolower($value);
}
Please or to participate in this conversation.