Laravel generate slug before save
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
Im trying to learn laravel 5 with help of this wonderful website. For my activity model, I want to generate slugs before I save one to my database so I've created the following model.
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Activity extends Model {
protected $table = 'activitys';
protected $fillable = [
'title',
'text',
'subtitle'
];
// Here I want to auto generate slug based on the title
public function setSlugAttribute(){
$this->attributes['slug'] = str_slug($this->title , "-");
}
//
}But when I save an object with help of the Activity model slug is not filled, I tried changing it to $this->attributes['title'] = "test" for testing but it didn't run. Also I tried adding parameters $title, $slug to setSlugAttribute() but it didn't help.
What am I doing wrong and could someone explain the parameter that is used in some examples for setSomeAttribute($whyParameterHere).
Note : there is a slug field in my database.
As suggested by user3158900, I've tried:
public function setTitleAttribute($title){
$this->title = $title;
$this->attributes['slug'] = str_slug($this->title , "-");
}
//This makes my title field empty but saves the slug the way I want it, why is $this->title empty then ? If I remove $this->title = $title; both title and slug are empty.
In Laravel, we use attributes to represent data for a given model. When using setters and getters in our models (also known as Accessors or Mutators), we can provide custom behavior when setting and retrieving data from these attributes. In the case of your Activity model, you want to generate a slug based on the title before saving it to the database. You need to modify your setSlugAttribute() function as follows:public function setTitleAttribute($title){
$this->attributes['slug'] = str_slug($title, '-');
}protected $fillable = [
'title',
'text',
'subtitle',
'slug'
];protected $fillable = [
'title',
'text',
'subtitle',
'slug'
];$model->save();
// Automatically updates title and slug attributes based on their relationship.