PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, February 8, 2022

[FIXED] Laravel - Eloquent: get posts from user with users post table

 February 08, 2022     eloquent, laravel, php, relation     No comments   

Issue

I searched a lot but could not find any answer about it, so I hope you could help me!

I have three tables: posts, users and post_users. Post_users contains two columns: user_id and post_id.

I need to get all posts by an user with Eloquent. Any ideas?


Solution

Model User:

public function posts()
{
  return $this->belongsToMany('App\Post', 'post_users', 'user_id', 'post_id');
}

Model Post:

public function users()
{
  return $this->belongsToMany('App\User', 'post_users', 'post_id', 'user_id');
}

Try:

$user = User::find($id);
$allpost = $user->posts()->get();
var_dump($allpost);


Answered By - mydo47
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing