Skip to content

Instantly share code, notes, and snippets.

@InnaTarasyan
Created November 29, 2025 16:37
Show Gist options
  • Select an option

  • Save InnaTarasyan/b903ee9455602be2fc47cbc7e6992bb8 to your computer and use it in GitHub Desktop.

Select an option

Save InnaTarasyan/b903ee9455602be2fc47cbc7e6992bb8 to your computer and use it in GitHub Desktop.
Trait for Auto Slugs on Create & Update
// 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