veksen
veksen

Reputation: 7003

Laravel : Using controller in included view

I have a view that is rendered with its controller. The function that calls the view is linked in my routes. It works fine when directly accessing the route, but obviously my controller is not included when I include it in my template.

How do I use my controller when I include my view?

I'm on Laravel 3.

Right now I have my controller :

public function get_current()
{
// $sales = ...
return View::make('sale.current')->with('sales',$sales);
}

My route (which obv only work on GET /current) :

Route::get('current', 'sale@current');

My master view

@include('sale.current')

Then my sale.current view calls $sales

@foreach($sales as $sale)

Thanks!

Upvotes: 1

Views: 3309

Answers (2)

Dhrumil Bhankhar
Dhrumil Bhankhar

Reputation: 1331

So this is the case when you want to call some laravel controller action from view to render another partial view. Although you can find one or another hack around it. However, please note that laravel controllers are not meant for that.

When you encounter this scenario when you want to reuse the same view again but don't want to supply all necessary data again & again in multiple controller actions, it's the time you should explore the Laravel View Composers.

Here is the official documentation link : https://laravel.com/docs/master/views#view-composers

Here is the more detailed version of it : https://scotch.io/tutorials/sharing-data-between-views-using-laravel-view-composers

This is the standard way of achieving it without any patch work.

Upvotes: 1

Darwing
Darwing

Reputation: 823

Your question is still unclear but I can try to help you. I did a small example with the requirements you gave. I create a route to an action controller as follows:

Route::get('test', 'TestController@test');

In TestController I define the action test as follows:

public function test()
{
  return View::make('test.home')->with('data', array('hello', 'world', '!'));
}

According to your asking, you defined a view who includes content from another view (layout) and in that layout you use the data passed for the action controller. I create the views as follows:

// home.blade.php
<h1>Message</h1>
@include('test.test')

and

// test.blade.php
<?php print_r($data); ?>

When I access to "test" I can see print_r output. I don't know if that is what you are doing, but in my case works fine.

I hope that can help you.

Upvotes: 0

Related Questions