duanrong3308 2018-09-26 14:10
浏览 74
已采纳

是否可以添加数据以从控制器构造函数中查看数据

I have a data that I want to return in all of my controller methods and I thought that'd be cleaner to return from the controller's constructor; because currently it's just repetitive return code.

protected $data;

public function __construct() {
   $this->data = "Test";
}

public function index() {
   // Stuff

   return view('test')->with([
       'testData' => $this->data
        // other view data
   ]);
}

public function store() {
   // Stuff

   return redirect()->back()->with([
       'testData' => $this->data
        // other view data
   ]);
}

This is just a pseudo example.

  • 写回答

5条回答 默认 最新

  • duanlu1950 2018-09-26 14:16
    关注

    Yes, that's possible. It's done exactly in the same manner you showed.

    However, I don't think that's the best way to do it. You might want to take a look into ViewComposers, which help provide a data set to a view (or multiple views) right after the controller but before the view is finally provided to the user.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办