|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Yard8\LaravelPermissions\Traits; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Support\Str; |
|
6
|
|
|
use Yard8\LaravelPermissions\Models\Permission; |
|
7
|
|
|
use Yard8\LaravelPermissions\Models\Role; |
|
8
|
|
|
|
|
9
|
|
|
trait HasPermissions |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* Check if a user has a specific permission assigned to them. |
|
13
|
|
|
* |
|
14
|
|
|
* @param string $permission |
|
15
|
|
|
* @return boolean |
|
16
|
|
|
*/ |
|
17
|
|
|
public function hasPermission($permission) |
|
18
|
|
|
{ |
|
19
|
|
|
if ($this->hasRole(config('permissions.admin'))) { |
|
20
|
|
|
return true; |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
$permissions = $this->permissions->pluck('id')->toArray(); |
|
|
|
|
|
|
24
|
|
|
|
|
25
|
|
|
return in_array($permission, $permissions); |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* Check if a user has any of the permissions assigned to them. |
|
30
|
|
|
* |
|
31
|
|
|
* @param array $permissions |
|
32
|
|
|
* @return boolean |
|
33
|
|
|
*/ |
|
34
|
|
|
public function hasAnyPermission($permissions) |
|
35
|
|
|
{ |
|
36
|
|
|
if ($this->hasRole(config('permissions.admin'))) { |
|
37
|
|
|
return true; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
$assignedPermissions = $this->permissions->pluck('id')->toArray(); |
|
41
|
|
|
|
|
42
|
|
|
foreach ($permissions as $permission) { |
|
43
|
|
|
if (in_array($permission, $assignedPermissions)) { |
|
44
|
|
|
return true; |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
return false; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* Check if a user has has one of the roles assigned to them. |
|
53
|
|
|
* |
|
54
|
|
|
* @param string|array $roles |
|
55
|
|
|
* @return boolean |
|
56
|
|
|
*/ |
|
57
|
|
|
public function hasRole($roles) |
|
58
|
|
|
{ |
|
59
|
|
|
if (is_null($this->role)) { |
|
|
|
|
|
|
60
|
|
|
return false; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
$role = Str::slug($this->role->name); |
|
64
|
|
|
|
|
65
|
|
|
if (is_array($roles)) { |
|
66
|
|
|
return in_array($role, $roles); |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
return $role === $roles; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
/** |
|
73
|
|
|
* Get the permissions assigned to the user. |
|
74
|
|
|
*/ |
|
75
|
|
|
public function permissions() |
|
76
|
|
|
{ |
|
77
|
|
|
return $this->belongsToMany(Permission::class); |
|
|
|
|
|
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
/** |
|
81
|
|
|
* Get the role assigned to the user. |
|
82
|
|
|
*/ |
|
83
|
|
|
public function role() |
|
84
|
|
|
{ |
|
85
|
|
|
return $this->belongsTo(Role::class); |
|
|
|
|
|
|
86
|
|
|
} |
|
87
|
|
|
} |
|
88
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: