Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 423 Vote(s) - 3.54 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Laravel 5 Controller Best Practices

#1
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.
Reply

#2
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
Reply

#3
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.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through