如何在Laravel中的构造方法中调用控制器方法



我正在尝试调用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:portalresourcesviewspageshome_partialsfeatured_news.blade.php)

如何在Laravel中添加多个部分数据以及刀片数据?

Laravel版本:7.30

您需要为此设置控制器属性,而不是将视图设置为方法,因此请找到以下有帮助的代码:

HomeController.php

class HomeController extends controller
{ 
private $news = []; 
public function __construct()
{
$this->middleware("auth");
$this->featuredNews();
}
public function index()
{
return view('pages.home')->with('news', $this->news);
}
public function featuredNews()
{
$this->news = News::select('id', 'heading', 'body', 'category', 'image', 'created_at', 'featured')->where('featured', 1)->first();
}
}

最新更新