Last active
November 22, 2016 03:14
-
-
Save cuonghuynh/a3ef2dc9457fe135aae61338dff43146 to your computer and use it in GitHub Desktop.
Handling Roles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Traits\User; | |
use App\Models\Role; | |
use App\Models\Permission; | |
use Illuminate\Database\Eloquent\ModelNotFoundException; | |
trait Roles { | |
public function roles() | |
{ | |
return $this->hasMany('App\Models\Role'); | |
} | |
//attach a role by name to a user | |
public function attach($role_name) | |
{ | |
try{ | |
$role = Role::where('name', '=', $role_name)->firstOrFail(); | |
//if the role already exists on a user, return false | |
if($this->isRole($role->name)) { | |
return false; | |
} | |
Permission::create([ | |
'user_id' => $this->id, | |
'role_id' => $role->id, | |
]); | |
return true; | |
} | |
catch(ModelNotFoundException $e) { | |
return false; | |
} | |
} | |
//check if a user is a certain role | |
public function isRole($role_name) | |
{ | |
try{ | |
$role = Role::where('name', '=', $role_name)->firstOrFail(); | |
Permission::where([ | |
'user_id' => $this->id, | |
'role_id' => $role->id, | |
])->firstOrFail(); | |
return true; | |
} | |
catch(ModelNotFoundException $e) { | |
return false; | |
} | |
} | |
} | |
// In Controller | |
/** | |
* Determine whether the user can view the post. | |
* | |
* @param \App\User $user | |
* @param \App\Study $study | |
* @return mixed | |
*/ | |
public function view(User $user, Post $post) | |
{ | |
return $user->isRole('admin'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment