【发布时间】:2021-06-28 00:21:58
【问题描述】:
我正在尝试在 laravel 控制器的 __construct 函数中调用多个方法,以便所有页面部分都可以在加载整个页面之前获取它们的数据。这是一些代码演示。
web.php
Route::get('/','HomeController@index');
HomeController.php
class HomeController extends controller
{
public function __construct()
{
$this->middleware("auth");
$this->featuredNews();
}
public function index()
{
return view('pages.home');
}
public function featuredNews()
{
$news = News::select('id', 'heading', 'body', 'category', 'image', 'created_at', 'featured')->where('featured', 1)->first();
return view('pages.home_partials.featured_news')->with('news', $news);
}
}
home.blade.php
@include("pages.home_partials.featured_news");
在这里,我期待 home.blade.php 数据以及 featured_news.blade.php 部分数据。但是这段代码抛出了一个错误
ErrorException
Undefined variable: news (View: D:\portal\resources\views\pages\home_partials\featured_news.blade.php)
如何在 Laravel 中添加多个部分数据以及刀片数据?
Laravel 版本:7.30
【问题讨论】:
-
stackoverflow.com/questions/67783719/… ,您要在所有刀片中传递数据吗?
-
不。例如,我只想将数据传递到单个刀片或单个网页中。但我想将其拆分为各种子模板并从不同的控制器渲染这些子模板数据,最后将它们全部包含到父刀片文件中。上面的示例显示在所有刀片中传递数据,我猜这对我的情况来说效率不高。