1 | <?php |
||
8 | trait HasRoles |
||
9 | { |
||
10 | /** |
||
11 | * A user may have multiple roles. |
||
12 | * |
||
13 | * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany |
||
14 | */ |
||
15 | public function roles() |
||
19 | |||
20 | /** |
||
21 | * Assign the given role to the user. |
||
22 | * |
||
23 | * @param string $role |
||
24 | * |
||
25 | * @return mixed |
||
26 | * @throws \Exception |
||
27 | */ |
||
28 | public function assignRole($role) |
||
29 | { |
||
30 | if (Role::count() === 0) { |
||
31 | throw new \Exception('No roles have been created.'); |
||
32 | } |
||
33 | |||
34 | return $this->roles()->save( |
||
35 | Role::whereName($role)->firstOrFail() |
||
36 | ); |
||
37 | } |
||
38 | |||
39 | /** |
||
40 | * Determine if the user has the given role. |
||
41 | * |
||
42 | * @param mixed $role |
||
43 | * @return bool |
||
44 | */ |
||
45 | public function hasRole($role) |
||
53 | |||
54 | /** |
||
55 | * Determine if the user may perform the given permission. |
||
56 | * |
||
57 | * @param Permission $permission |
||
58 | * @return bool |
||
59 | */ |
||
60 | public function hasPermission(Permission $permission) |
||
64 | } |
||
65 |
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: