martinbean/laravel-sluggable-trait

一个特性,你可以将其应用到Eloquent模型上,以便在保存时自动生成slug。

0.4.0 2022-05-03 14:20 UTC

This package is auto-updated.

Last update: 2024-08-30 01:11:31 UTC


README

一个特性,你可以将其应用到Eloquent模型上,以便在保存时自动生成slug。

安装

composer require martinbean/laravel-sluggable-trait

使用

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use MartinBean\Database\Eloquent\Sluggable;

class Item extends Model
{
    use Sluggable;
}

默认情况下,该特性假设你的数据库有两个列:nameslug。如果你需要更改这些,你可以重写getter方法

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use MartinBean\Database\Eloquent\Sluggable;

class Item extends Model
{
    use Sluggable;

    protected function getSlugColumnName()
    {
        return 'seo_title';
    }

    protected function getSluggableString()
    {
        return 'headline';
    }
}

注意: 此包的0.4.0版本中,这些方法的可见性已从 public 更改为 protected

getSlugColumnName() 方法应返回你想要在数据库表中存储slug的列名。

getSluggableString() 应返回你想要创建slug的字符串。这作为一个方法暴露,而不是属性或常量,因为可能需要从多个列的值创建slug。例如

/**
 * Create a string based on the first and last name of a person.
 */
protected function getSluggableString()
{
    return sprintf('%s %s', $this->first_name, $this->last_name);
}
/**
 * Create a string based on a formatted address string.
 */
protected function getSluggableString()
{
    return implode(', ', array_filter([
        $this->street_address,
        $this->locality,
        $this->region,
        $this->postal_code,
        $this->country,
    ]));
}

配置

默认情况下,该包将在slug中使用破折号作为单词分隔符,即 this-is-your-slug。分隔符字符可以通过发布包的配置文件并指定自己的分隔符字符来更改。

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

然后你可以在发布的 config/sluggable.php 文件中将分隔符值更改为类似下划线的东西

<?php
// config/sluggable.php

return [

    'separator' => '_',

];

注意: 更改slug分隔符 不会 更改你数据库中的任何现有slug。如果你更改分隔符,你需要手动更新这些。

许可证

根据 MIT 许可证 许可。