如何将来自不同 controllers/actions 的数据发送到同一视图?

How to send data from different controllers/actions to the same view?

这是我第一次使用 Laravel,到目前为止,我在将数据传递给视图时遇到了一些困难。我的应用程序是一个单页网站,顶部有一个菜单,列出所有产品类别,下面是每个项目或产品的缩略图网格。访问者可以按他们选择的类别过滤产品。

Route::get('home/{category}', array('as'=>'itemshome', 'uses'=>'ItemsController@index'));

所以在我的 ItemsControllers 中,我从项目模型中获取一些项目并将它们传递给视图。

class ItemsController extends \BaseController {


public function index($category)
{
    return View::make('home/index', ['items' => Item::where('publishtime', '<', 
 date('Y-m-d H:i:s'))->where('category_id','=',$category)->paginate(24)]);

}

此时我不确定是否应该使用 ItemsController 将数据从 Category 模型发送到主视图,或者定义一个新的 CategoryController 并从那里传递值是否是更好的方法.

您不能只使用另一个控制器在同一个请求期间将数据发送到同一个视图。

要么将其添加到视图中进行调用:

return View::make('home/index', [
    'items' => Item::where('publishtime', '<', date('Y-m-d H:i:s'))->where('category_id','=',$category)->paginate(24),
    'categories' => Category::all()
];

或者,如果类别数据实际上与项目控制器无关但视图需要,您可以注册一个 view composer

View::composer('home/index', function($view){
    $view->with('categories', Category::all());
});

现在每次渲染 home/index 视图时,都会注入 categories

您实际上可以将视图编辑器放置在您想要的任何位置。但是我建议您添加一个新文件 app/composers.php 来存储您所有的视图作曲家。然后你需要把它包含在某个地方。例如在底部的 app/start/global.php 中:

require app_path().'/composers.php';