努诺·马杜罗
发布
Laravel Sluggable
, a package for automatic slug generation on Eloquent models. Rather than reaching for a trait or a base class, the package uses a single PHP attribute
#[Sluggable]
, placed directly on the model.
Beyond the basics, it covers the edge cases that tend to surface in real apps: collision handling, scoped uniqueness (per-tenant, per-locale), multi-column sources, soft-deleted record collisions, and full Unicode and CJK transliteration.
立即开始
通过 Composer 安装软件包:
作曲家
要求
nunomaduro/laravel-sluggable
笔记: This package requires PHP 8.5+ and Laravel 13.5+
The quickest way to wire up a model is the included
make:sluggable
Artisan 命令:
php
工匠
make:sluggable
邮政
It reads your model's table schema, picks the most likely source column (
title
,
name
,
headline
, 或者
subject
), adds the
#[Sluggable]
attribute to the model class, and creates a migration in
database/migrations
:
使用
NunoMaduro\LaravelSluggable\Attributes\Sluggable
;#[
Sluggable
(
从
:
'标题'
)]班级
邮政
延伸
模型{}
架构
::
桌子
(
'帖子'
,
功能
(
蓝图
$table) {$表
->
细绳
(
'slug'
)
// ->nullable()
->
独特的
()
->
后
(
'ID'
(英文):});
Review the migration before running it. You may need to make the column nullable if the table already has rows before you run
php artisan migrate
。
After that, slug generation is automatic:
$post
=
邮政
::
创造
([
'标题'
=>
'Laravel News Rocks'
]);$post
->
slug;
// "laravel-news-rocks"
配置
All options live on the attribute itself. The
from
和
to
parameters control which columns are read and written, and
from
accepts an array when you want to combine multiple columns:
#[
Sluggable
(
从
:[
'名'
,
'姓'
],
到
:
'slug'
)]班级
作者
延伸
模型
{}$author
=
作者
::
创造
([
'名'
=>
“约翰”
,
'姓'
=>
'Tolkien'
]);$author
->
slug;
// "john-tolkien"
For multi-tenant apps or anything with per-scope uniqueness, pass a
scope
column (or an array of columns):
#[
Sluggable
(
从
:
'标题'
,
范围
:
'team_id'
)]
Other notable options include
maxLength
to cap slug length,
separator
to swap out the dash, and
onUpdating
to regenerate the slug whenever the source column changes. By default, slugs are locked after creation — manually assigned slug values are always preserved regardless of this setting.
错误处理
If a slug cannot be generated, the package throws a
CouldNotGenerateSlugException
. In HTTP contexts, it automatically renders as a
422
response with a validation-style error payload, so it drops into existing error handling without extra work. The error key defaults to the source column name but can be overridden via
errorKey
. Because it extends
ValidationException
, it won't show up in your application logs.
Unicode Support
The pipeline transliterates non-Latin scripts to readable Latin slugs and is domain-aware — values that look like hostnames or file paths keep their dots intact instead of being collapsed to dashes.
You can learn more about Laravel Sluggable on the projects GitHub repo.







