定制 philiprehberger/laravel-slug-generator 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

philiprehberger/laravel-slug-generator

Composer 安装命令:

composer require philiprehberger/laravel-slug-generator

包简介

Automatic slug generation for Eloquent models with scoped uniqueness, history, and transliteration

README 文档

README

Tests Latest Version on Packagist Last updated

Automatic slug generation for Eloquent models with scoped uniqueness, history, and transliteration.

Requirements

  • PHP 8.2+
  • Laravel 11 or 12

The PHP intl extension is recommended for best transliteration results (falls back to iconv then a simple strip).

Installation

composer require philiprehberger/laravel-slug-generator

The service provider is auto-discovered via Laravel's package discovery. No manual registration is required.

Publish configuration

php artisan vendor:publish --tag=slug-generator-config

This creates config/slug-generator.php in your application.

Publish and run the slug history migration (optional)

Only required if you intend to use the HasSlugHistory trait.

php artisan vendor:publish --tag=slug-generator-migrations
php artisan migrate

Usage

Basic Usage

Add the HasSlug trait to any Eloquent model:

use Illuminate\Database\Eloquent\Model;
use PhilipRehberger\SlugGenerator\Concerns\HasSlug;

class Post extends Model
{
    use HasSlug;
}

The trait reads from the title column by default and writes to slug:

$post = Post::create(['title' => 'Hello World']);
echo $post->slug; // 'hello-world'

Duplicate slugs automatically receive a numeric suffix:

Post::create(['title' => 'Hello World']); // slug: 'hello-world'
Post::create(['title' => 'Hello World']); // slug: 'hello-world-2'

Per-Model Overrides

class Article extends Model
{
    use HasSlug;

    public function slugSource(): string|array  { return 'title'; }
    public function slugField(): string          { return 'slug'; }
    public function slugSeparator(): string      { return '-'; }
    public function slugMaxLength(): ?int        { return null; }
    public function slugShouldBeUnique(): bool   { return true; }
    public function slugUniqueScope(): ?string   { return null; }
    public function slugOnUpdate(): bool         { return false; }
}

Scoped Uniqueness

class Post extends Model
{
    use HasSlug;

    public function slugUniqueScope(): ?string
    {
        return 'category_id';
    }
}

Slug Template

Use a template pattern to control how attributes are combined in the slug:

class Author extends Model
{
    use HasSlug;

    public function slugTemplate(): ?string
    {
        return '{last_name}-{first_name}';
    }
}

$author = Author::create(['first_name' => 'John', 'last_name' => 'Doe']);
echo $author->slug; // 'doe-john'

Placeholders use the {attribute} syntax and are resolved from model attributes before slugification. Missing or null attributes are omitted from the result.

Slug History and Redirects

use PhilipRehberger\SlugGenerator\Concerns\HasSlug;
use PhilipRehberger\SlugGenerator\Concerns\HasSlugHistory;

class Post extends Model
{
    use HasSlug;
    use HasSlugHistory;

    public function slugOnUpdate(): bool { return true; }
}

Use findBySlugOrRedirect() in controllers to handle current and old slugs transparently:

public function show(string $slug): Response
{
    $result = Post::findBySlugOrRedirect($slug);

    if ($result === null) { abort(404); }

    if (is_array($result) && $result['redirect']) {
        return redirect(route('posts.show', $result['slug']), 301);
    }

    return view('posts.show', ['post' => $result]);
}

API

HasSlug Trait — Override Methods

Method Return Type Default Description
slugSource() string|array 'title' Source column(s) to generate slug from
slugField() string 'slug' Database column to store the slug
slugSeparator() string '-' Word separator
slugMaxLength() ?int null Max length; truncates at word boundary
slugShouldBeUnique() bool true Enforce unique slugs
slugUniqueScope() ?string null Column to scope uniqueness checks
slugTemplate() ?string null Template pattern with {attribute} placeholders
slugOnUpdate() bool false Regenerate slug on model update

HasSlugHistory Trait

Method Description
Post::findBySlugOrRedirect(string $slug) Returns model, redirect array, or null
->slugHistories MorphMany relationship to slug history records

SlugRedirectMiddleware Parameters

Position Name Description
1 modelClass Fully-qualified model class (must use HasSlugHistory)
2 routeParam Route parameter name that holds the slug (default: slug)
3 urlPrefix URL prefix for the redirect target (default: /)

Development

composer install
vendor/bin/phpunit
vendor/bin/pint --test
vendor/bin/phpstan analyse

Support

If you find this project useful:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT

philiprehberger/laravel-slug-generator 适用场景与选型建议

philiprehberger/laravel-slug-generator 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 62 次下载、GitHub Stars 达 1, 最近一次更新时间为 2026 年 03 月 09 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「url」 「seo」 「slug」 「laravel」 「eloquent」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 philiprehberger/laravel-slug-generator 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 philiprehberger/laravel-slug-generator 我们能提供哪些服务?
定制开发 / 二次开发

基于 philiprehberger/laravel-slug-generator 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 62
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 33
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-09