Skip to content

Slug

Overview

The Slug trait (HasSlug) enables route model binding using URL-friendly slugs instead of UUIDs. When applied to a model, routes automatically resolve by slug while the database column stores the original value.

How It Works

php
use App\Traits\Common\HasSlug;

class Article extends Model
{
    use HasSlug;

    // Default slug column is 'slug'
    // Override by setting a property:
    protected ?string $slug = 'custom_slug_column';
}

Once applied, route bindings like /articles/my-article-title automatically resolve to the correct model.

Key Behaviors

BehaviorDescription
getRouteKeyName()Returns the slug column name
getRouteKey()Returns a slugified version of the column value
resolveRouteBinding()Matches incoming slugs case-insensitively
Custom columnSet $slug property to use a column other than slug

Key Files

app/Traits/Common/HasSlug.php