【问题标题】:What is the right way to adding extra fields in laravel-spatie package?在 laravel-spatie 包中添加额外字段的正确方法是什么?
【发布时间】:2020-06-19 09:23:33
【问题描述】:

1 天前我开始尝试学习如何使用 laravel spatie 包,但现在我有点困惑在 spatie 包中添加额外字段的正确方法是什么。我尝试按照 spatie web 的文档来扩展模型,这是我的代码。

迁移架构

Schema::create($tableNames['roles'], function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('color');
            $table->string('description');
            $table->string('guard_name');
            $table->timestamps();
        });

覆盖模型

<?php

namespace App\Models;

use Spatie\Permission\Models\Role as SpatieRole;

class Role extends SpatieRole
{
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $this->mergeFillable(['color', 'description']);
    }
}

控制器测试

class RoleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $role = Role::where('name', 'Super Admin')->first();
        $roleAdmin = Role::where('name', 'Admin')->first();

        if (!$role) {
            Role::create([
                'name' => 'Super Admin',
                'color' => 'Black',
                'description' => 'Manage all the role and permission in the system'
            ]);
        }
        if (!$roleAdmin) {
            Role::create([
                'name' => 'Admin',
                'color' => 'Red',
                'description' => 'Manage users in the system'
            ]);
        }
        return Role::paginate(20);
    }

我的代码现在运行良好,但我真的很想知道我是否做错了或有更好的方法。总的来说,我还是 php 和 laravel 的新手,非常感谢~

【问题讨论】:

    标签: php laravel eloquent laravel-permission


    【解决方案1】:
    1. 您需要创建角色表吗?最好扩展而不是重新创建表,以防 Package 对核心迁移进行更改。
            Schema::table($tableNames['roles'], function (Blueprint $table) {
                $table->string('color');
                $table->string('description');
            });
    

    另外,如果您要拥有几个像上面这样的属性,最好为这些属性添加一个单独的表。

    1. 我不确定您为什么要在 index() 方法中添加新角色,我假设是为了测试。如果是用于测试,我建议将代码重构为以下内容:
    $roles = [[
        'name' => 'Super Admin',
        'color' => 'Black',
        'description' => 'Manage all the role and permission in the system'
    ], [
        'name' => 'Admin',
        'color' => 'Red',
        'description' => 'Manage users in the system'
    ]];
    
    foreach($roles as $role) {
        Role::firstOrCreate($role);
    }
    
    return new RoleResource::collection(Role::all());
    

    您可能希望首先使用 Laravel Seeders 来播种角色。另外,如果你的角色比你的角色少,你可能不需要paginate() 方法。

    【讨论】:

    • 非常感谢您回答问题。 1. 是的,我不是自己重新创建表,我只是关注默认情况下从命令创建模式的位置,然后我在那里添加一些额外的字段。在这一步,我仍然不知道这是否是在那之后做的正确方法。 2. 是的,我只是为了测试目的而创建的,哦,我明白了,我会注意到总是在播种机类中制作。再次感谢~
    猜你喜欢
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 2023-01-19
    • 2022-08-14
    • 2019-09-10
    • 1970-01-01
    • 2020-07-27
    • 2017-04-03
    相关资源
    最近更新 更多