How to include a sub-view in Laravel using a distinct controller?

2k Views Asked by At

There are many threads dealing with sub-views, with many various answers. And I didn't really find a matching answer, although I guess my pattern is quite usual:

A page displays results from a query. The results area can be updated with Ajax by user interactions. Therefore, I have two controllers:

  1. pageDisplay, which renders the overall view (without the results)
  2. resultsDisplay, which generates and renders the results using a sub-view

My question deals with the initial display of the results with default settings. How can I call the resultsDisplay controller from the pageDisplay ?

There are a couple of options I can't (or don't want to) use:

  • An initial Ajax request, as this solution is not efficient considering SEO
  • Including the sub-view using @include as the main view does not know the appropriate variables to send to the sub-view. Those variables are generated by the resultsDisplaycontroller
  • Duplicating the code of the resultsDisplaycontroller into the pageDisplaycontroller. This is so ugly and harder to maintain...

Maybe I could call the sub-controller from the main one. But I don't know how to do that since the sub-controller returns a view...

Thanks for your kind assistance!

1

There are 1 best solutions below

0
On

I think what you're after is nest() to nest a child view. Here's an example:

// Show view and nest sub view passing $foo and $bar to sub view
$foo = 'Some foo data';
$bar = 'Some bar data';
View::make('pageDisplay')->nest('child', 'resultsDisplay', compact('foo', 'bar));

Then in your pageDisplay view you would simply echo out the nested view:

<div id="myChildView">
    {{ $child }}
</div>

And in your child view you could use the $foo and $bar variables you've passed through.

Check out the official docs (under Passing A Sub-View To A View) here: http://laravel.com/docs/responses#views