italofantone / slugable
这是一个基于 Laravel 设计的 PHP 库,旨在简化并自动化基于 URL 的 slugs 的创建。
v1.1.0
2024-09-20 18:47 UTC
Requires
- php: ^8.1
- illuminate/database: ^11.0
- illuminate/support: ^11.0
Requires (Dev)
- orchestra/testbench: ^9.2
- phpunit/phpunit: ^11.3
README
这是一个基于 Laravel 设计的 PHP 库,旨在简化并自动化基于 URL 的 slugs 的创建。
⚠️ 此代码仅供教学目的 [...]
安装
您可以通过 composer 安装 slugable 包。运行以下命令
composer require italofantone/slugable
用法
- 将特质添加到您的模型中
要使用 Slugable 功能,请将 Slugable 特质包含在您的 Eloquent 模型中。以下是一个示例
<?php
namespace App\Models;
use Italofantone\Slugable\Slugable;
use Illuminate\Database\Eloquent\Model;
class Lesson extends Model
{
use Slugable;
protected $fillable = ['title', 'body'];
}
迁移示例:您需要创建 slug 字段。
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('lessons', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('slug')->unique();
$table->text('body');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('lessons');
}
};
- 自定义分隔符:运行以下命令。
php artisan vendor:publish --tag=slugable-config
您可以在 config/slugable.php
文件中自定义 slug 分隔符。例如
<?php
return [
/**
* The field that will be used to generate the slug.
* e.g. 'my title' will be converted to 'my-title'.
*
* Default: '-'.
*/
'separator' => '-',
];
这将更改生成 slugs 时使用的默认分隔符。
- 自定义 slug 源字段
您可以通过在您的模型中设置受保护的 $slugSourceField
属性来自定义用于生成 slug 的属性。
示例:
要使用名称属性而不是默认属性(如标题),请执行以下操作
<?php
namespace App\Models;
use Italofantone\Slugable\Slugable;
use Illuminate\Database\Eloquent\Model;
class Lesson extends Model
{
use Slugable;
protected $fillable = ['name', 'body'];
protected $slugSourceField = 'name';
}
在此配置下,slug 将基于 name
属性生成。
联系方式
- 电子邮件:i@rimorsoft.com
- Twitter:@italofantone
- LinkedIn:italofantone
捐赠
如果您觉得这个项目很有用并想支持其开发,您可以通过 PayPal 进行捐赠
- PayPal: 通过 PayPal 捐赠
感谢您的支持!