Reputation: 376
I'm using Lumen as REST API. I have a Post model and a Comment Model.
Post.php
public function comments(){
return $this->hasMany('App\Comment');
}
Comment.php
public function post(){
return $this->belongsTo('App\Post');
}
I also have Resource controllers for both these models. If I want to get all the comments on a particular post, where do I write that logic? In the PostController (because I'll be filtering comments by Post) or in the CommentController (because I'm fetching comments after all)? Which is the better way? Or is there some other way altogether (like creating a separate controller) ? I just want to get the structure right and write clean code. Any help will be greatly appreciated.
Upvotes: 1
Views: 1417
Reputation: 1309
It depends on the requirements actually and how are you handling the data. Normally, no comments display on the post listing page. so it would be better just to send posts without comments which means the logic will be in post controller. For post details page you will be sending the post with comments so the logic would still be in Post Controller. Something like this:
Post::where('id', $id)->with('comments')->first();
It would be in comments controller if you just need to send comments for specific post without post object.
Comment::where('post_id', $post_id)->get();
If you have any confusion ask me.
Upvotes: 1
Reputation: 1944
I personally like to follow a pattern whereby a controller doesn't have any custom methods. Thus you end up with lots of very thin controllers with generic resource methods like index
update
store
create
edit
destroy
.
so for you example
I would have /Posts/CommentController.php
with resource methods
Upvotes: 2