Laravel adding hasRole method to Auth

 


adding the following to your User model:-

public function hasRole($role)
{
    return User::where('role', $role)->get();
}

This should firstly check to see if you User table has the field 'role' and then check your parameter $role against the role field.

You can the check by doing the following:

if( Auth::user()->hasRole($role) )

You may need to adjust the example to your needs. Let me know if you need anything else.

/------------EDIT-----------------/

If you have two seperate tables, one holding the user information and the other holding the users privileges/roles you could add another function to the User model:

public function userID()
{
    return $this->user_id; 
}

This will check for if you have a user ID field if so, it will return the id for the authenticated user.

Then add this to your hasRoles method:

    public function hasRoles($userID, $roles)
{
    return Your\User\Roles\Model::where('role', $role)->where('user_id', $user_id)->get();
}

Your middleware would look like this:

public function handle($request, Closure $next, $role)
{
    if ($this->auth->guest()) {
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('login');
        }
    }

    $userID = Auth::user()->userID();

    if (auth()->check() && auth()->user()->hasRole($userID, $role)) {
        return $next($request);
    }

}

Comments

Popular posts from this blog

Target class controller does not exist - Laravel 8