Created
November 29, 2025 16:37
-
-
Save InnaTarasyan/b903ee9455602be2fc47cbc7e6992bb8 to your computer and use it in GitHub Desktop.
Trait for Auto Slugs on Create & Update
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // app/Traits/HasSlug.php | |
| namespace App\Traits; | |
| use Illuminate\Support\Str; | |
| trait HasSlug | |
| { | |
| protected static function bootHasSlug() | |
| { | |
| static::saving(function ($model) { | |
| if (! $model->slug || $model->isDirty('title')) { | |
| $model->slug = Str::slug($model->title); | |
| } | |
| }); | |
| } | |
| } | |
| // In your model: | |
| use App\Traits\HasSlug; | |
| class Post extends Model | |
| { | |
| use HasSlug; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment