Simple trait to automatically add slugs to eloquent models

Published Nov 05 2024

Just add this trait to your model and you should be good to go. Modify if you need more complex logic.

<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

trait HasSlug
{
    protected static function bootHasSlug(): void
    {
        static::creating(function (Model $model) {
            $attr = $model->sluggable_attribute ?? 'title';
            $model->slug = Str::slug($model->{$attr});
        });

        static::updating(function (Model $model) {
            $attr = $model->sluggable_attribute ?? 'title';
            $model->slug = Str::slug($model->{$attr});
        });
    }
}