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

Swaz's avatar
Level 20

Auto generate a slug

I have a "Name" field that has to be unique. I want to generate a slug from that name. Is this the best way to go about it? It seems a bit hacky to me.

public function setNameAttribute($name)
{
    $this->attributes['name'] = $name;
    $this->attributes['slug'] = Str::slug($name);
}
0 likes
4 replies
jangaraev's avatar

I have a very short and handy trait to automate this.

use Illuminate\Support\Str;

trait HasSlug
{
    public static function bootHasSlug()
    {
        static::saving(function ($model) {
            if (empty($model->slug) && $model->title) {
                $this->slug = strtolower(Str::slug($model->title));
            }
        });
    }
}
johnDoe220's avatar

It is good to use the package, but for such a case, the package is not recommended at all. Please do not convert Laravel to WordPress

public function slug($data)
    {
        $ex = explode(' ', $data);
        return implode('-', $ex);
    }

    public function store(Request $request)
    {
        Post::create([
            'slug' => $this->slug($request->title),
            'body' => $request->contents
        ]);
        return back();
    }

Please or to participate in this conversation.