Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

twg_'s avatar
Level 6

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.

0 likes
5 replies
Ishra's avatar
Ishra
Best Answer
Level 6
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);
}
1 like
Amaury's avatar

@ishra @twg_ " Attribute" not "Argument"!!!

public function setTitleAttribute($value) 
{
    $this->attributes['title'] = mb_strtolower($value);
}
1 like
Ishra's avatar

ah ofcourse, you are correct. Thanks for checking, i updated my answer.

twg_'s avatar
Level 6

Hey @ishra,

Thanks for the code snippets. I was able to accomplish what I wanted with:

public static function boot()
{
	parent::boot();
	static::creating(function ($detail) {
            $detail->key = \Str::slug($detail->key, '_');
        });
}
1 like

Please or to participate in this conversation.