【发布时间】: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