Call to a member function roles() on null Laravel

2019-07-21 21:20发布

I'm making user roles function in Laravel and everything has worked fine and from nowhere I have error: call to a member function roles() or null.

This is my html from where I'm sending request:

<td><input type="checkbox" {{ $user->hasRole('User') ? 'checked' : '' }} name="role_user"></td>
<td><input type="checkbox" {{ $user->hasRole('Author') ? 'checked' : '' }} name="role_author"></td>
<td><input type="checkbox" {{ $user->hasRole('Admin') ? 'checked' : '' }} name="role_admin"></td>

Then there are function where I'm making relationship between model User and model Role, and functions where I'm checking the roles:

 public function roles(){
        return $this->belongsToMany('App\Role','role_user','user_id','role_id');
    }

  public function hasAnyRole($roles){
        if(is_array($roles)){
            foreach ($roles as $role){
                if($this->hasRole($role)){
                    return true;
                }
            }
        }else{
            if($this->hasRole($roles)){
                return false;
            }
        }
        return false;
    }


    public function hasRole($role){
        if($this->roles->where('name',$role)->first()){
            return true;
        }
        return false;
    }

And in the end the function where I'm assing new roles:

public function postAdminAssignRoles(Request $request)
    {
        $user = User::where('email', $request['email'])->first();
        $user->roles()->detach();
        if ($request['role_user']) {
            $user->roles()->attach(Role::where('name', 'User')->first());
        }
        if ($request['role_author']) {
            $user->roles()->attach(Role::where('name', 'Author')->first());
        }
        if ($request['role_admin']) {
            $user->roles()->attach(Role::where('name', 'Admin')->first());
        }
        return redirect()->back();
    }

I have no idea why this is not working now, because everything was working fine till now. Any ideas?

1条回答
疯言疯语
2楼-- · 2019-07-21 22:04

I guess error occurs in postAdminAssignRoles method.

Probably user with an email that you try to fetch does not exist in database and thus calling first() method returns null.

You might want to use firstOrFail() instead to clearly see that email is invalid. Or after fetching model with first() add if (! $user) { ... } and do whatever, like redirect, in case you don't want to display an error.

查看更多
登录 后发表回答