我需要幫助傳遞我已初始化__construct()用于在 Laravel 中查看的變數。
這是我的控制器代碼
protected $profileInfo;
public function __construct(){
$this->profileInfo = Profile::with('address')->where('id', '=', '1')->get();
}
public function index(){
$this->profileInfo;
return view('admin_pages.profile', compact('profileInfo'));
}
我收到一個錯誤undefined variable profileInfo
uj5u.com熱心網友回復:
使用時使用compact()的引數必須定義為變數:
protected $profileInfo;
public function __construct(){
$this->profileInfo = Profile::with('address')->where('id', '=', '1')->get();
}
public function index(){
$profileInfo = $this->profileInfo;
return view('admin_pages.profile', compact('profileInfo'));
}
在這種情況下compact(),將創建一個這樣的陣列:
[ 'profileInfo' => $this->profileInfo ]
uj5u.com熱心網友回復:
compact()在當前符號表中查找具有該名稱的變數并將其添加到輸出陣列中,以便變數名稱成為鍵,變數的內容成為該鍵的值。
compact您可以傳遞這樣的陣列,而不是使用:
protected $profileInfo;
public function __construct(){
$this->profileInfo = Profile::with('address')->where('id', '=', '1')->get();
}
public function index(){
return view('admin_pages.profile', ['profileInfo' => $this->profileInfo]);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/531403.html
下一篇:Laravel自動洗掉相關行
