/
Role.php
112 lines (90 loc) · 2.55 KB
/
Role.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
namespace Encore\Admin\Auth\Database;
use Encore\Admin\Traits\DefaultDatetimeFormat;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Role extends Model
{
use DefaultDatetimeFormat;
protected $fillable = ['name', 'slug'];
/**
* Create a new Eloquent model instance.
*
* @param array $attributes
*/
public function __construct(array $attributes = [])
{
$connection = config('admin.database.connection') ?: config('database.default');
$this->setConnection($connection);
$this->setTable(config('admin.database.roles_table'));
parent::__construct($attributes);
}
/**
* A role belongs to many users.
*
* @return BelongsToMany
*/
public function administrators(): BelongsToMany
{
$pivotTable = config('admin.database.role_users_table');
$relatedModel = config('admin.database.users_model');
return $this->belongsToMany($relatedModel, $pivotTable, 'role_id', 'user_id');
}
/**
* A role belongs to many permissions.
*
* @return BelongsToMany
*/
public function permissions(): BelongsToMany
{
$pivotTable = config('admin.database.role_permissions_table');
$relatedModel = config('admin.database.permissions_model');
return $this->belongsToMany($relatedModel, $pivotTable, 'role_id', 'permission_id');
}
/**
* A role belongs to many menus.
*
* @return BelongsToMany
*/
public function menus(): BelongsToMany
{
$pivotTable = config('admin.database.role_menu_table');
$relatedModel = config('admin.database.menu_model');
return $this->belongsToMany($relatedModel, $pivotTable, 'role_id', 'menu_id');
}
/**
* Check user has permission.
*
* @param $permission
*
* @return bool
*/
public function can(string $permission): bool
{
return $this->permissions()->where('slug', $permission)->exists();
}
/**
* Check user has no permission.
*
* @param $permission
*
* @return bool
*/
public function cannot(string $permission): bool
{
return !$this->can($permission);
}
/**
* Detach models from the relationship.
*
* @return void
*/
protected static function boot()
{
parent::boot();
static::deleting(function ($model) {
$model->administrators()->detach();
$model->permissions()->detach();
});
}
}