Loyd
1 month ago
211
4
Laravel

get auth user followers via pivot table

Posted 1 month ago by Loyd

Hi Devs.

I have a pivot user_profile table that I use to follow or unfollow a profile.

user model

public function following()
    {
        return $this->belongsToMany(Profile::class);
    }

profile model

public function followers()
    {
    	return $this->belongsToMany(User::class);
    }

to get the auth user followings I just do

public function following()
    {
    	$following = auth()->user()->following()->with('user')->get();

    	return view('following', compact('following'));
    }

and it works well.

However, if I want to do the inverse

 public function followers()
    {
    	$followers = auth()->user()->profile()->followers()->get();

    	return view('followers', compact('followers'));
    }

ie to get the auth user followers am getting an error BadMethodCallException Call to undefined method Illuminate\Database\Eloquent\Relations\HasOne::followers()

Please sign in or create an account to participate in this conversation.