Changing model values using mutators before saving in database

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.

Related Posts


Using WhereIn

Updating multiple rows

Using Like

Using orWhere

What is Query Builder?

Using "with" in eloquent query

Getting last inserted id

Selecting last row of a table

Using parameters in find() method

Using local scope in eloquent

Using global scope in eloquent