我希望初始化一個特定的變數并在類中重用它,而不需要在類中一次又一次地重寫整個代碼。
$profileInfo = Profile::with('address')->where('id', '=', '1')->get();
上面的變數是我想要重用的。
我嘗試使用建構式
protected $profileInfo;
public function __construct(Profile $profileInfo){
$this->profileInfo = Profile::with('address')->where('id', '=', '1')->get();
}
public function index($profileInfo){
$this->profileInfo;
dd($profileInfo);
}
但是Too few arguments to function App\Http\Controllers\ProfileController::index(), 0 passed當我在瀏覽器中加載刀片視圖時,我進入了顯示。
請問有什么幫助嗎?
uj5u.com熱心網友回復:
您遇到了麻煩,因為您正在混合概念。依賴注入、本地實體變數,可能還有路由模型系結或路由變數系結。
依賴注入要求 Laravel 為你提供一個類的實體。在 Laravel 加載某些東西的情況下,它通常會嘗試使用 DI 來填充未知數。對于您的建構式,您要求 LaravelProfile在變數 name 下為建構式提供一個新的類實體$profileInfo。你最終不會在建構式中使用這個變數,所以在這里請求它是沒有意義的。
接下來(仍在建構式中)設定區域變數并將其分配給profileInfo控制器類實體。
繼續前進,當路由嘗試觸發該index方法時,有一個$profileInfo. Laravel 不知道這是什么,并且它與路由中的任何內容都不匹配(請參閱檔案中的路由模型系結)。因此,您會收到“引數太少”的訊息。如果此變數不存在,您應該profileInfo早先設定。
如果要保留區域變數,可以執行以下操作:
protected $profileInfo;
public function __construct(){
$this->profileInfo = Profile::with('address')->where('id', '=', '1')->get();
}
public function index(){
dd($this->profileInfo);
}
這是另一個建議供您考慮...
由于這稱為組態檔,因此我們似乎應該向用戶模型詢問適當的組態檔記錄。
// in your user model, set up a relationship
public function profile(){
return $this->hasOne(Profile::class);
}
// In controller, if you're getting a profile for the logged in user
public function index(){
$profile = Auth::user()->profile;
dd($profile);
}
// In controller, if you're getting profile for another user via route model binding
public function index(User $user){
$profile = $user->profile;
dd($profile);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/531406.html
標籤:php拉拉维尔
