Sometimes we need to change model value before saving in the database. With help of mutators we can achieve this desired result and It are described below.
Suppose if we need to create slug of a title for Post model before saving it to database and we can use mutator to achieve this result.
// In App/Models/Post.php
// at the top use Illuminate\Support\Str; public function setTitleAttribute($value) { $this->attributes['slug'] = Str::slug($value); }
Above, slug() method of Str facade is used to generate slug before saving it to posts table of database from value of title.