anyone?
Where to place the logic for permissions
Hey artisans!
I started off by creating a very simple permissions solution. I added a 'role' column in the users table and depending on what integer it was, the user would have a defined role. Then in the user model, I defined something like this:
public function hasRoleOfAdmin()
{
return ($this->role == 3);
}
public function hasRoleOfEditor()
{
return ($this->role == 2);
}
Then in some controllers I do something as simple as:
if (Auth::check() && Auth::user()->hasRoleOfAdmin())
I also made some simple middlewares that looks like this:
public function handle($request, Closure $next)
{
if(auth()->check() && auth()->user()->hasRoleOfAdmin())
{
return $next($request);
}
return redirect('/');
}
I decided to make it more flexible so I followed Jeff's series on ACL in Laravel: Part 3: https://laracasts.com/series/whats-new-in-laravel-5-1/episodes/15 and created the whole solution with roles, permissions tables and permission_role and role_user pivot tables.
Now I'm a bit confused. Where would be a good place to place the business logic that replaces my current solution? If anyone that has followed the series could guide me in the right direction and give some tips and examples so that I learn, it would mean a whole lot. Thanks folks!
Yes, assuming that hasPermission($permission) exists as a method on your User model you should be good to go.
//User model
public function hasPermission($permission){
$role = $this->role;
$role->hasPermission($permission); //I would choose to delegate this task to the same method name on Role model. Otherwise your User model 'knows too much' about the Role model. Personal taste though :)
}
//Role model
public function hasPermission($requiredPermission){
$permissions = $this->permissions;
foreach($permissions as $permission){
if($requiredPermission == $permission){
return true; //returns true early if the permission is found (as it doesnt need to continue)
}
}
//if none are found then it will eventually reach this
return false;
}
Please or to participate in this conversation.