php - Laravel . Using two controllers in the same view

I am really new to laravel. So i am just working on a simple project. I built a Postscontroller that has it's views . So the problem is i wanna extend this to having comments in the view_one_post.blade.php view. So i should create CommentsController but i am not sure how to list the comments using CommentsController@index and i am not sure what view this method should return because i am using the comments in the same view of posts which is view_one_post.blade.php ? I have seen some answers to this question but it just doesn't match my case
Answer
Solution:
You should be able to achieve this with a View Composer. You can create a view for the comments which can be included in any other views. A View Composer will allow you to bind data to this view before it is rendered.
use App\Comment;
use Illuminate\View\View;
class CommentsComposer
{
protected $comment;
public function __construct(Comment $comment)
{
$this->comment = $comment;
}
public function compose(View $view)
{
$view->with('comments', $this->comment->latest()->take(10)->get());
}
}
In a Service Provider'sboot
method you can attach the composer to your view:
View::composer('partials.commments', 'App\Composers\CommentsComposer');
Anywhere you want to use that view you can just include it in Blade:
@include('partials.comments')
This allows you to have an isolated place for the logic of handling the data that is needed for this view partial and it only needs to worry about that one responsibility. Unlike a Controller a Composer doesn't need to worry about handling the request or response.
Laravel 7.x Docs - Views - View ComposersView::composer
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: the browser (or proxy) sent a request that this server could not understand.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.