hyperlink/laravel-sluggable

为每个模型创建永久的SEO友好slug

dev-main 2023-02-28 10:58 UTC

This package is auto-updated.

Last update: 2024-08-28 14:19:22 UTC


README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

为每个模型创建永久的SEO友好slug

安装

您可以通过composer安装此包

composer require hyperlink/laravel-sluggable

您可以使用以下命令发布和运行迁移

php artisan vendor:publish --tag="laravel-sluggable-migrations"
php artisan migrate

您可以使用以下命令发布配置文件

php artisan vendor:publish --tag="laravel-sluggable-config"

这是已发布配置文件的内容

return [
    /*
     * The name of the table that will store the slugs.
     */
    'table' => 'slugs',

    /*
     * The name of the column that will store the slug.
     */
    'column' => 'slug',

    /*
     * The separator used to separate words in the slug.
     * ATTENTION: If you change this value
     * no existing slugs will be changed.
     */
    'separator' => '-',

    /*
     * The separator used to separate the slug from the counter.
     * If the slug already exists, a counter will be added.
     * ATTENTION: If you change this value
     * no existing slugs will be changed.
     */
    'counter_separator' => '_',

    /*
     * The max length of the slug excluding the counter.
     * ATTENTION: If you change this value to above 255
     * you must also publish the migration and
     * change column type in the database.
     */
    'max_length' => 255,

    /*
     * The model that will be used to generate the slug.
     * You can use your own model by extending the provided model.
     */
    'model' => Hyperlink\Sluggable\Models\Slug::class,
];

用法

class Post extends Model
{
    use Sluggable; // Add this trait to your model

    // The column that will be used to generate the slug
    protected string $slugCreatedFrom = 'title';
}

该特性会注册一个观察者,当模型创建或更新时将生成slug。

    public static function bootSluggable(): void
    {
        // ...
        static::created(/* ... */);

        static::updated(/* ... */);
        // ...
    }

您可以使用以下方式重写它

protected function makeSlug(): string
{
    return (string) sluggable($this->{$this->getSlugCreatedFrom()});
}

测试

composer test

安全漏洞

请查阅我们的安全策略了解如何报告安全漏洞。

鸣谢

许可

MIT许可(MIT)。更多信息请参阅许可文件