1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace PhpCollective\MenuMaker\Storage; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Model; |
6
|
|
|
use Illuminate\Database\Eloquent\Builder; |
7
|
|
|
use PhpCollective\MenuMaker\Scopes\ActiveRoleScope; |
8
|
|
|
|
9
|
|
|
class Role extends Model |
10
|
|
|
{ |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* The table associated with the model. |
14
|
|
|
* |
15
|
|
|
* @var string |
16
|
|
|
*/ |
17
|
|
|
protected $table = 'pcmm_roles'; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Attributes that should be mass-assignable. |
21
|
|
|
* |
22
|
|
|
* @var array |
23
|
|
|
*/ |
24
|
|
|
protected $fillable = [ |
25
|
|
|
'name', |
26
|
|
|
'is_active', |
27
|
|
|
'is_admin' |
28
|
|
|
]; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* The number of models to return for pagination. |
32
|
|
|
* |
33
|
|
|
* @var int |
34
|
|
|
*/ |
35
|
|
|
protected $perPage = 10; |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* The group's default attributes. |
39
|
|
|
* |
40
|
|
|
* @var array |
41
|
|
|
*/ |
42
|
|
|
protected $attributes = [ |
43
|
|
|
'is_active' => true, |
44
|
|
|
'is_admin' => false |
45
|
|
|
]; |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* The attributes that should be cast to native types. |
49
|
|
|
* |
50
|
|
|
* @var array |
51
|
|
|
*/ |
52
|
|
|
protected $casts = [ |
53
|
|
|
'is_active' => 'integer', |
54
|
|
|
'is_admin' => 'integer' |
55
|
|
|
]; |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* The "booting" method of the model. |
59
|
|
|
* |
60
|
|
|
* @return void |
61
|
|
|
*/ |
62
|
|
|
protected static function boot() |
63
|
|
|
{ |
64
|
|
|
parent::boot(); |
65
|
|
|
|
66
|
|
|
static::saved(function ($group) { |
67
|
|
|
if($group->is_admin) |
68
|
|
|
{ |
69
|
|
|
static::where('is_admin', true) |
70
|
|
|
->where('id', '!=', $group->id) |
71
|
|
|
->update(['is_admin' => false]); |
72
|
|
|
} |
73
|
|
|
}); |
74
|
|
|
|
75
|
|
|
static::addGlobalScope(new ActiveRoleScope); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* Scope a query to only include popular users. |
80
|
|
|
* |
81
|
|
|
* @param \Illuminate\Database\Eloquent\Builder $query |
82
|
|
|
* @param boolean $status |
83
|
|
|
* @return \Illuminate\Database\Eloquent\Builder |
84
|
|
|
*/ |
85
|
|
|
public function scopeAdmin(Builder $query, $status = true) |
86
|
|
|
{ |
87
|
|
|
return $query->where('is_admin', $status); |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
/** |
91
|
|
|
* The users that associates with the group. |
92
|
|
|
*/ |
93
|
|
|
public function users() |
94
|
|
|
{ |
95
|
|
|
return $this->belongsToMany(config('auth.providers.users.model'), 'pcmm_role_user', 'role_id', 'user_id'); |
96
|
|
|
} |
97
|
|
|
|
98
|
|
|
/** |
99
|
|
|
* Get the menus that related with the group. |
100
|
|
|
*/ |
101
|
|
|
public function menus() |
102
|
|
|
{ |
103
|
|
|
return $this->belongsToMany(Menu::class, 'pcmm_menu_role'); |
104
|
|
|
} |
105
|
|
|
} |
106
|
|
|
|