Call to a member function pluck() on null

We got the error call to a member function pluck() on null, when we called pluck method on null. So before calling pluck method check if the variable is empty or not after that call pluck method else it will return an error message call to a member function pluck() on null.

Answers 1
  • Call pluck method on $user->followings to get followings in Overtrue\LaravelFollow

    $user = Auth::user();
    if($user->followings){
        $followings = $user->followings->pluck('id');
    }else{
        $followings = array();
    }
    
    $users = User::whereNotIn('id', $followings)
            ->where('id', '<>', $user->id)
            ->get();
    
    0

    In my case I have called the $user->followings->pluck(‘id’) to the whereNotIn() query and got the error because there are no followings for the logged in user in the table. So the $user->followings method returns the null value so that is why we got the error calling a member function pluck() on null. 

    After that i have checked following if it is null then we pass empty array to pluck method 

  • Back to code snippet queries related laravel