I know this isn't the answer that you are looking for, but maybe you should try Entrust from Zizaco, is one of the best authentication solutions in Laravel.
Oct 17, 2016
5
Level 54
HasPermission Method For Roles And Users
So I'm trying to figure out what I should do in this situation. I was told I should remove the hasPermission method to my Role class. Is this something that anyone can verify would be the best choice for this.
I was told this as the explanation.
Add hasPermission method to Role Class also and call it here. So that you keep the scope of the object limited to it's own relations only.
/**
* Checks to see if the currently authenticated user has permission to edit users and if they can edit the requested user through a lesser important role.
*
* @param User $authenticatedUser
* @param User $user
*
* @return bool
*/
public function edit(User $authenticatedUser, User $user) {
return $authenticatedUser->hasPermission('edit-a-user') && ($authenticatedUser->role->importance > $user->role->importance);
}
<?php
namespace App\Traits;
use App\Models\Role;
trait HasRoles {
/**
* Relationship between a user and their role.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function role() {
return $this->belongsTo(Role::class);
}
/**
* Verifies user has specified role.
*
* @return boolean
*/
public function hasRole($role)
{
if (is_string($role)) {
return $this->role->slug === $role;
}
return $role->contains('slug', $this->role->slug);
}
/**
* Verifies user has specified permission.
*
* @return boolean
*/
public function hasPermission($permission) {
return $this->role->permissions->contains('slug', $permission);
}
}
Please or to participate in this conversation.