alhaji-aki/laravel-uuid

创建模型时生成uuid的特质

1.0.3 2022-05-10 04:24 UTC

This package is auto-updated.

Last update: 2024-09-10 10:04:22 UTC


README

MIT Licensed GitHub Workflow Status

此包提供了一种特质,当保存任何Eloquent模型时,将生成一个唯一的uuid。

$model = new EloquentModel();
$model->name = 'activerecord is awesome';
$model->save();
echo $model->uuid; // outputs a uuid

安装

您可以通过composer安装此包

composer require alhaji-aki/laravel-uuid

用法

您的Eloquent模型应使用AlhajiAki\LaravelUuid\HasUuid特质。

特质包含一个抽象方法getUuidColumn(),您必须自行实现。

您的模型迁移应该有一个字段来保存uuid。

以下是如何实现特质的示例

namespace App;
use AlhajiAki\LaravelUuid\HasUuid;
use Illuminate\Database\Eloquent\Model;
class YourEloquentModel extends Model
{
    use HasUuid;

    /**
     * Get the column to save the generated uuid to.
     */
    public function getUuidColumn() : string
    {
        return 'uuid';
    }
}

及其迁移

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateYourEloquentModelTable extends Migration
{
    public function up()
    {
        Schema::create('your_eloquent_models', function (Blueprint $table) {
            $table->increments('id');
            $table->string('uuid'); // Field name same as what you return in `getUuidColumn`
            $table->string('name');
            $table->timestamps();
        });
    }
}

在路由中使用别名

要在路由中使用生成的uuid,请记住使用Laravel的隐式路由模型绑定

namespace App;
use AlhajiAki\LaravelUuid\HasUuid;
use Illuminate\Database\Eloquent\Model;
class YourEloquentModel extends Model
{
    use HasUuid;

    /**
     * Get the column to save the generated uuid to.
     */
    public function getUuidColumn() : string
    {
        return 'uuid';
    }
    /**
     * Get the route key for the model.
     *
     * @return string
     */
    public function getRouteKeyName()
    {
        return 'uuid';
    }
}

重写别名

您也可以通过将其设置为与生成的别名不同的值来重写生成的别名。

$model = EloquentModel::create(['name' => 'my name']); //slug is now "my-name";
$model->slug = 'my-custom-url';
$model->save(); //slug is now "my-custom-url";

测试

composer test

贡献

请参阅贡献指南以获取详细信息。

安全

如果您发现任何与安全相关的问题,请通过电子邮件abdulkudus2922@gmail.com而不是使用问题跟踪器。

鸣谢

此包受到Spatie Laravel Sluggable的启发。

许可证

MIT许可证(MIT)。请参阅许可证文件以获取更多信息。