1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace MultiTenantLaravel\App\Models; |
4
|
|
|
|
5
|
|
|
use Illuminate\Notifications\Notifiable; |
6
|
|
|
use Illuminate\Foundation\Auth\User as Authenticatable; |
7
|
|
|
use Illuminate\Support\Collection; |
8
|
|
|
|
9
|
|
|
abstract class BaseUser extends Authenticatable |
10
|
|
|
{ |
11
|
|
|
use Notifiable; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* The attributes that are mass assignable. |
15
|
|
|
* |
16
|
|
|
* @var array |
17
|
|
|
*/ |
18
|
|
|
protected $fillable = [ |
19
|
|
|
'name', 'email', 'password', |
20
|
|
|
]; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* The attributes that should be hidden for arrays. |
24
|
|
|
* |
25
|
|
|
* @var array |
26
|
|
|
*/ |
27
|
|
|
protected $hidden = [ |
28
|
|
|
'password', 'remember_token', |
29
|
|
|
]; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Return all of the tenants this user is the owner of |
33
|
|
|
*/ |
34
|
|
|
public function roles() |
35
|
|
|
{ |
36
|
|
|
return $this->belongsToMany( |
37
|
|
|
config('multi-tenant.role_class'), |
38
|
|
|
'multi_tenant_role_user', |
39
|
|
|
'user_id', |
40
|
|
|
'multi_tenant_role_id' |
41
|
|
|
); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Assign a given role to a user |
46
|
|
|
*/ |
47
|
|
|
public function assignRole(BaseRole $role) |
48
|
|
|
{ |
49
|
|
|
$this->roles()->syncWithoutDetaching([$role->id]); |
50
|
|
|
|
51
|
|
|
return $this; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Check if a user has a given role |
56
|
|
|
*/ |
57
|
|
|
public function hasRole($role) |
58
|
|
|
{ |
59
|
|
|
if (is_string($role)) { |
60
|
|
|
return $this->roles->contains('name', $role); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
if ($role instanceof Collection) { |
64
|
|
|
$role = $role->toArray(); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
if (is_array($role)) { |
68
|
|
|
foreach($role as $r) { |
69
|
|
|
if ($this->roles->contains('name', $r['name'])) { |
70
|
|
|
return true; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
return $this->roles()->where('multi_tenant_role_id', $role->id)->exists(); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* Return all of the tenants this user is the owner of |
80
|
|
|
*/ |
81
|
|
|
public function owns() |
82
|
|
|
{ |
83
|
|
|
return $this->hasMany(config('multi-tenant.tenant_class'), 'owner_id'); |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
/** |
87
|
|
|
* Return the currently active tenant for this user based on the session |
88
|
|
|
*/ |
89
|
|
|
public function activeTenant() |
90
|
|
|
{ |
91
|
|
|
return config('multi-tenant.tenant_class')::findOrFail(session()->get('tenant.id')); |
92
|
|
|
} |
93
|
|
|
|
94
|
|
|
/** |
95
|
|
|
* The tenants relationship |
96
|
|
|
*/ |
97
|
|
|
public function tenants() |
98
|
|
|
{ |
99
|
|
|
return $this->belongsToMany(config('multi-tenant.tenant_class')); |
100
|
|
|
} |
101
|
|
|
} |
102
|
|
|
|