ryancco/laravel-uuid-models

此包已被废弃,不再维护。没有建议的替代包。

用于处理具有 UUID 路由键的 Eloquent 模型的特性

2.0 2021-04-24 06:17 UTC

This package is auto-updated.

Last update: 2023-08-24 11:43:11 UTC


README

Latest Version on Packagist Build Status

Laravel UUID Models

此包提供了一个简单的 特性,用于在 Laravel Eloquent 模型中使用,以提供用于 UUID 路由键的即插即用解决方案(而不是自增 ID)。

安装

唯一支持的自动化安装方式是通过 Composer

composer require ryancco/laravel-uuid-models

使用方法

安装包后,您可以将该特性添加到任何您希望具有 UUID 路由键的 Eloquent 模型中。

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Ryancco\HasUuidRouteKey\HasUuidRouteKey;

class Post extends Model
{
    use HasUuidRouteKey;
}

接下来,为这些模型的数据库表添加一个列来存储 UUID;以下是一个示例迁移

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddUuidColumnToPostsTable extends Migration
{
    public function up(): void
    {
        Schema::table('posts', static function (Blueprint $table) {
            $table->uuid('uuid');
        });
    }
}

现在,您可以像使用自增 ID 路由键一样使用配置好的 UUID 属性作为路由键。

路由

<?php
// Route registration works exactly as it had with models routed by the "id" attribute

// "binded" routes
Route::get('posts/{post}', 'PostController@show');

// resourceful routes
Route::resource('posts', 'PostController');

// ...

测试

<?php

namespace Tests\Feature;

use App\Models\Post;
use Tests\TestCase;

class PostsControllerTest extends TestCase
{
    public function testAdminsHavePermissionToViewPrivatePosts(): void
    {
        $post = factory(Post::class)->state('private')->create();

        $this->get(route('posts.view', $post))->assertOk();
        // route('posts.view', $post->uuid) - localhost/posts/94205252-7c44-4e5b-ad75-682ac81fea84
    }
}

配置

默认情况下,路由键名为 'uuid',但您可以将其配置为所需的任何名称。

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Ryancco\HasUuidRouteKey\HasUuidRouteKey;

class Post extends Model
{
    use HasUuidRouteKey;

    public function getRouteKeyName() : string
    {
        return 'something-else';
    }
}

注意事项

需要注意的一点是,UUID 的生成是在模型事件 "creating" 触发时触发的。需要记住的最重要的事情,以及为什么是这样,是因为在通过 new 关键字实例化模型时不会生成 UUID,而是在将其持久化到(或从)数据库中检索后。

如果需要在 "creating" 模型事件触发之前生成 UUID,可以手动调用以下方法

<?php

$post = new App\Models\Post();
$post->generateUuidRouteKey();

假设所有路由都是使用 route() 辅助函数生成的,所有路由都将正常工作。

贡献

请通过创建 问题拉取请求(鼓励,但不是必需的)来报告任何问题。