1

This is my Controller method wherein I want to fetch posts by user id. I also have relationship defined in User model

public function posts()
{
    return $this->hasMany('Post','user_id','id');
}

UserController.php

use App\Post;
public function findPostsByUser($id){
    $user = User::findOrFail($id);    
    $posts = $user->posts()->get();
    return $posts;
}

But it is giving me 'Post' not found error. Can someone help on this.

2
  • 1
    Please update this first >hasMany('Post','user_id','id') to >hasMany('App\Post','user_id','id') Commented Mar 2, 2019 at 12:59
  • If you wont to get only posts use Post::where('user_id', $id)->get() Commented Mar 2, 2019 at 13:15

2 Answers 2

2

In your Post model make sure you have the relation defined like this:


public function user()
{
    return $this->belongsTo('App\User');
}

And change your User model to this:

public function posts()
{
    return $this->hasMany('App\Post','user_id','id');
}
Sign up to request clarification or add additional context in comments.

Comments

2

Change relation method to

use App\Post;
....
public function posts()
{
    return $this->hasMany(Post::class,'user_id','id');
}

or

public function posts()
{
    return $this->hasMany('App\Post','user_id','id');
}

If you wont to get only posts that case use this

public function findPostsByUser($id){
    $posts = Post::where('user_id', $id)->get();
    return $posts;
} 

The second solution has 1 query, but first solution has 2 query in db.

Also you can do it this way

public function findPostsByUser($id){
    $posts = Post::whereUserId($id)->get();
    return $posts;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.