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

How to invoke controller methods in construct method in 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:\portal\resources\views\pages\home_partials\featured_news.blade.php)

如何在 Laravel 中添加多个分音数据以及 blade 数据?

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();
 }
}