Nov 05 2024

Simple trait to add slugs to eloquent models


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

1<?php
2 
3namespace App\Traits;
4 
5use Illuminate\Database\Eloquent\Model;
6use Illuminate\Support\Str;
7 
8trait HasSlug
9{
10 protected static function bootHasSlug(): void
11 {
12 static::creating(function (Model $model) {
13 $attr = $model->sluggable_attribute ?? 'title';
14 $model->slug = Str::slug($model->{$attr});
15 });
16 
17 static::updating(function (Model $model) {
18 $attr = $model->sluggable_attribute ?? 'title';
19 $model->slug = Str::slug($model->{$attr});
20 });
21 }
22}