Laravel-5 adding hasRole method to Auth

前端 未结 3 1432
情话喂你
情话喂你 2021-02-06 16:03

I\'m trying to extend the Laravel-5.1 Auth middleware so that I can add my own method to it:

Auth::hasRole()

What do I need to do in or

相关标签:
3条回答
  • 2021-02-06 16:20

    Could you try 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);
        }
    
    }
    

    If I understood correctly what you want. I believe this should work for you.

    0 讨论(0)
  • 2021-02-06 16:22

    There are some good packages to help with this if you don't want to brew your own. I can recommend both: Zizaco Entrust: https://github.com/Zizaco/entrust and Sentinel: https://cartalyst.com/manual/sentinel/2.0

    0 讨论(0)
  • 2021-02-06 16:35

    I've taken a different tack by using a trait in my User model.

    <?php
    namespace App\Traits;
    
    use App\Role;
    use App\User;
    
    trait HasRoles{
        public function roles()
        {
            return $this->belongsToMany('App\Role');
        }
    
        public static function findByRole(Role $role)
        {
            return $role->users()->get();
        }
    
        public function hasRole(Role $role)
        {
            return $this->roles()->get()->contains($role);
        }
    }
    
    0 讨论(0)
提交回复
热议问题