1 | <?php |
||
2 | |||
3 | namespace jeremykenedy\LaravelRoles\Traits; |
||
4 | |||
5 | use Illuminate\Database\Eloquent\Collection; |
||
6 | use Illuminate\Database\Eloquent\Relations\BelongsToMany; |
||
7 | |||
8 | trait RoleHasRelations |
||
9 | { |
||
10 | /** |
||
11 | * Role belongs to many permissions. |
||
12 | * |
||
13 | * @return BelongsToMany |
||
14 | */ |
||
15 | public function permissions() |
||
16 | { |
||
17 | return $this->belongsToMany(config('roles.models.permission'))->withTimestamps(); |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
18 | } |
||
19 | |||
20 | /** |
||
21 | * Role belongs to many users. |
||
22 | * |
||
23 | * @return BelongsToMany |
||
24 | */ |
||
25 | public function users() |
||
26 | { |
||
27 | return $this->belongsToMany(config('roles.models.defaultUser'), config('roles.roleUserTable'))->withTimestamps(); |
||
28 | } |
||
29 | |||
30 | /** |
||
31 | * Attach permission to a role. |
||
32 | * |
||
33 | * @param int|Permission $permission |
||
34 | * |
||
35 | * @return int|bool |
||
36 | */ |
||
37 | public function attachPermission($permission) |
||
38 | { |
||
39 | return (!$this->permissions()->get()->contains($permission)) ? $this->permissions()->attach($permission) : true; |
||
40 | } |
||
41 | |||
42 | /** |
||
43 | * Detach permission from a role. |
||
44 | * |
||
45 | * @param int|Permission $permission |
||
46 | * |
||
47 | * @return int |
||
48 | */ |
||
49 | public function detachPermission($permission) |
||
50 | { |
||
51 | return $this->permissions()->detach($permission); |
||
52 | } |
||
53 | |||
54 | /** |
||
55 | * Detach all permissions. |
||
56 | * |
||
57 | * @return int |
||
58 | */ |
||
59 | public function detachAllPermissions() |
||
60 | { |
||
61 | return $this->permissions()->detach(); |
||
62 | } |
||
63 | |||
64 | /** |
||
65 | * Sync permissions for a role. |
||
66 | * |
||
67 | * @param array|Permission[]|Collection $permissions |
||
68 | * |
||
69 | * @return array |
||
70 | */ |
||
71 | public function syncPermissions($permissions) |
||
72 | { |
||
73 | return $this->permissions()->sync($permissions); |
||
74 | } |
||
75 | } |
||
76 |