Sven B Sven B - 5 months ago 80
PHP Question

Laravel generate slug before save

Im trying to learn laravel 5 with help of this wondefull 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 = [

// 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 didnt run. Also I tried adding parameters $title, $slug to setSlugAttribute() but it didnt 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


I believe this isn't working because you aren't trying to set a slug attribute so that function never gets hit.

I'd suggest setting $this->attributes['slug'] = ... in your setTitleAttribute() function so it runs whenever you set a title.

Otherwise, another solution would be to create an event on save for your model which would set it there.

Edit: According to comments, it's also necessary to actually set the title attribute in this function as well...

public function seTitleAttribute($value)
    $this->attributes['title'] = $value;
    $this->attributes['slug'] = str_slug($value);