Dale
Dale

Reputation: 580

User Following System in Laravel

I'm learning laravel atm and trying to implement a twitter style follower feed. So far I have the following

standard users table (id, username ect)

subscriptions (aka followers) table that contains user_id, subscriber_id, timestamps

My User model contains the following relationship

public function subscriptions()
{
    return $this->belongsToMany('App\User', 'subscriptions', 'user_id', 'subscriber_id')->withTimestamps();
}
    

    public function subscribers()
{
    return $this->belongsToMany('App\User', 'subscriptions', 'subscriber_id', 'user_id')->withTimestamps();
}

I am now trying to load a users list of subscriptions ie. User 14 follows user 15

$subscriber = Auth::user()->id;
    
        
        $user = User::find($subscriber);
        
        
        $userids = $user->subscriptions->lists('user_id');

        return $userids;

I use this code to fetch the current logged in user and find their subscriptions. $userids should return a list of IDs that the current logged in user is subscribed to. However it just produces an empty array despite the records existing in the DB. (it should return 15, but returns only [] )

Am I going wrong somehere or missing out on something?

Upvotes: 1

Views: 1226

Answers (2)

abdullah ghanem
abdullah ghanem

Reputation: 11

Get the current user's subscribers using:

$subscribers = Auth::user()->subscribers;

and you can send subscribers to any view and use

@foreach ($subscribers as subscriber)
   {{ $subscriber->name }}
@endforeach

Upvotes: 1

Merhawi Fissehaye
Merhawi Fissehaye

Reputation: 2827

Using the lists method call you are asking to return a user_id column from the results of subscriptions method call. However the subscriptions call returns a relationship object that gives results from the users table not the pivot table subscriptions. The user_id column is found only on the pivot table and not on the users table. That's why you are getting empty result. Here I am getting an array with NULL values. Try with: $userids = $user->subscriptions->lists('id');

Upvotes: 0

Related Questions