使用 Laravel 在控制器中使用私有变量

Posted

技术标签:

【中文标题】使用 Laravel 在控制器中使用私有变量【英文标题】:use private variable in controller with 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,我想提供一个私有变量,这可能吗? 提前致谢 ! :)

【问题讨论】:

【参考方案1】:

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

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

【讨论】:

【参考方案2】:

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

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

【讨论】:

以上是关于使用 Laravel 在控制器中使用私有变量的主要内容,如果未能解决你的问题,请参考以下文章