/
Role.php
82 lines (68 loc) · 1.9 KB
/
Role.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
namespace Bican\Roles\Models;
use Bican\Roles\Traits\Slugable;
use Illuminate\Database\Eloquent\Model;
use Bican\Roles\Traits\RoleHasRelations;
use Bican\Roles\Contracts\RoleHasRelations as RoleHasRelationsContract;
class Role extends Model implements RoleHasRelationsContract {
use Slugable, RoleHasRelations;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'slug', 'description', 'level'];
/**
* Create a new model instance.
*
* @param array $attributes
* @return void
*/
public function __construct(array $attributes = []) {
parent::__construct($attributes);
if ($connection = config('roles.connection')) {
$this->connection = $connection;
}
}
/**
* app/Support/helpers.php
*
* Get a permission by slug and attach it.
*
* @param string $slug
*
* @return Role|bool true when succeed
*/
public static function getRoleFromSLug($slug) {
$role = Role::where('slug', $slug)->first();
if (! is_null($role))
return $role;
return false;
}
/**
* @return \App\User[]
*/
public function usersInRole() {
return $this->users()->get()->all();
}
/**
* @return Permission[]
*/
public function getPermissions() {
return $this->permissions()->get()->all();
}
public function getPermissionsSLugs() {
$p = $this->getPermissions();
$a = array();
foreach ($p as $perm)
array_push($a, $perm->slug);
return $a;
}
public function users() {
return $this->belongsToMany('App\User', 'role_user', 'role_id', 'user_id');
}
public function permissions() {
// $related, $table = null, $foreignKey = null, $otherKey = null, $relation = null
return $this->belongsToMany('Bican\Roles\Models\Permission', 'permission_role', 'role_id', 'permission_id');
}
}