php - User Follow/Subscription Relationship Model In Laravel -


i trying create youtube style subscription model application. i've had small amounts of success far, being can follow other users , stores following in database. having trouble retrieving list of people current user following.

the database:

users table (id, first_name, last_name, email, password, token, timestamps)

subscriptions table (id, user_id, subscriber_id, timestamps)

user model:

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 using code retrieve of current users subscriptions (aka following)

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

now, code returning null value. on further investigation makes sense query being run incorrect

sql query:

select `user_id` `users` inner join `subscriptions` on `users`.`id` = `subscriptions`.`subscriber_id` `subscriptions`.`user_id` = 14 

my current set trying wrong thing.

if user 1 follows users 2, 3 , 4 code should return 2, 3 , 4.

can please correct relationship set or code running? should looking user_id in subscriptions table based on current users subscriber_id.

laravel 5.3 eloquent relationships

if check code @ end of many-to-many relationships part, see line of code.

return $this->belongstomany('app\role', 'role_user', 'user_id', 'role_id'); 

here, have 'role_user' pivot (relationship) table, 'user_id' foreign key in relationship table , primary key in user model, , 'role_id' foreign key in relationship table , primary key in roles model.

so when try this:

public function subscriptions() {  return $this->belongstomany('app\user', 'subscriptions', 'user_id',       'subscriber_id')->withtimestamps(); } 

you taking 'subscriber_id' foreign key in relationship table , primary key subscriber. since function trying subscriptions, reaching subscriber id's won't work. why when changed them worked.

the result should this:

public function subscribers() {  return $this->belongstomany('app\user', 'subscriptions', 'user_id',       'subscriber_id')->withtimestamps(); }  public function subscriptions() { return $this->belongstomany('app\user', 'subscriptions', 'subscriber_id',  'user_id')->withtimestamps(); } 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -