Call to a Member Function Pluck() on null

Asked

Viewed 192 times

0

In the following code, the following error occurs, which I cannot understand why:

Call to a Member Function Pluck() on null

public function edit($id)

    {
        $user = User::find($id);
        $roles = Role::pluck('name','name')->all();
        $userRole = $user->roles->pluck('name','id')->all();
        return view('users.edit',compact('user','roles','userRole'));
    }
  • Welcome Albino, this would help you: https://stackoverflow.com/questions/52800750/call-to-a-member-function-pluck-on-null?

  • on which line is the error?

1 answer

0

The mistake happened because the $user->roles returned null, that is, apparently this user has no relationship with Role. I suggest you take a treatment before using the method pluck().

public function edit($id)
{
    $user = User::find($id);
    $roles = Role::pluck('name','name')->all();
    $userRole = null;
    if (count($user->roles) > 0) {
       $userRole = $user->roles->pluck('name','id')->all();
    }

    return view('users.edit',compact('user','roles','userRole'));
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.