首頁  >  問答  >  主體

Laravel控制器中如何初始化給定的函數

我希望初始化一個特定的變數並在類別中重用它,而不需要在類別中一次又一次地重寫整個程式碼。

$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少的參數到函數 App\Http\Controllers\ProfileController::index(), 0 Passed

請幫忙嗎?

P粉404539732P粉404539732257 天前263

全部回覆(1)我來回復

  • P粉627027031

    P粉6270270312024-01-11 14:11:54

    您遇到麻煩是因為您混淆了概念。依賴注入、本地實例變量,以及可能的路由模型綁定或路由變數綁定。

    依賴注入要求 Laravel 為您提供一個類別的實例。在 Laravel 載入某些內容的情況下,它通常會嘗試使用 DI 來填充未知數。對於建構函數,您要求 Laravel 為建構子提供變數名稱 $profileInfo 下的 Profile 類別的新實例。您最終不會在建構函數中使用此變量,因此沒有必要在此處請求它。

    接下來(仍在建構函數中)設定局部變數 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);
    }
    

    回覆
    0
  • 取消回覆