【问题标题】:How to invoke controller methods in construct method in Laravel?如何在 Laravel 的构造方法中调用控制器方法?
【发布时间】: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/… ,您要在所有刀片中传递数据吗?
  • 不。例如,我只想将数据传递到单个刀片或单个网页中。但我想将其拆分为各种子模板并从不同的控制器渲染这些子模板数据,最后将它们全部包含到父刀片文件中。上面的示例显示在所有刀片中传递数据,我猜这对我的情况来说效率不高。

标签: laravel laravel-7


【解决方案1】:

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

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

【讨论】:

  • 嗯,它会将 $news 返回给home.blade.php,但我可以在featured_news.blade.php 中访问这些数据吗?请注意,home.blade.php 是具有许多子组件(!)的父刀片文件,例如 feature.blade.php
  • 是的,如果您使用@inlcude 指令,您也可以在子视图中访问它。
猜你喜欢
  • 2013-08-08
  • 1970-01-01
  • 1970-01-01
  • 2015-03-13
  • 2014-05-02
  • 1970-01-01
  • 1970-01-01
  • 2016-11-20
  • 2019-04-30
相关资源
最近更新 更多