【问题标题】:use private variable in controller with Laravel使用 Laravel 在控制器中使用私有变量
【发布时间】:2020-07-31 15:03:38
【问题描述】:
private $cart;

public function __construct() {
    $this->cart = DB::table('carts')->get();
}

public function index(){
    return view('carts.index')->with(compact('$this->cart));
}

我正在使用 Laravel,我想提供一个私有变量,这可能吗? 提前致谢 ! :)

【问题讨论】:

    标签: php laravel oop object view


    【解决方案1】:

    您可以不使用compact 并自己创建数组:

    ...->with(['cart' => $this->cart]);
    

    【讨论】:

      【解决方案2】:

      您可以在函数中传递该变量,无需将其声明为私有。

      public function index(){
          return view('carts.index')->with(['cart' => DB::table('carts')->get()]);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-06
        • 2018-10-31
        • 2015-01-15
        • 1970-01-01
        • 2013-02-25
        • 2014-06-20
        • 2014-04-19
        • 2016-03-28
        相关资源
        最近更新 更多