I am making a blog with users who each have posts. Naturally, I have a UserController, PostController, and a User and Post model.
The User model has a one-to-many relationship with the Post model like so
// User Model
public function posts()
{
return $this->hasMany('App\Post');
}
I would like to get all the posts of a specific user by using
// UserController or PostController...
$posts = User::find($id)->posts()->get()
Should I write this logic in my UserController (because it uses the User model) or should I write the logic in my PostController (because it returns posts)?
Actually, you just need to create the relationship as you did, and then you will be able call it wherever you want, just like as you described, with User::find($id)->posts()->get()
.
So, if you need to return a user's post on a view, for instance, you can do something like that on your UserController:
public function postsView(User $user)
{
$posts = $user->posts()->get();
return view('user.posts', compact('posts'));
}
Also, if you want the other way around (to know who is the user behind the post), you can create a relationship on your Post model using belongsTo()
.
// Post Model
public function user()
{
return $this->belongsTo('App\User');
}