Heim  >  Fragen und Antworten  >  Hauptteil

So initialisieren Sie eine bestimmte Funktion im Laravel-Controller

Ich möchte eine bestimmte Variable initialisieren und in der Klasse wiederverwenden, ohne den gesamten Code in der Klasse immer wieder neu schreiben zu müssen.

$profileInfo = Profile::with('address')->where('id', '=', '1')->get();

Die oben genannten Variablen möchte ich wiederverwenden.

Ich habe versucht, den Konstruktor zu verwenden

protected $profileInfo;

public function __construct(Profile $profileInfo){
   $this->profileInfo = Profile::with('address')->where('id', '=', '1')->get();
}
public function index($profileInfo){
  $this->profileInfo;
  dd($profileInfo);
}

Aber wenn ich die Blade-Ansicht im Browser lade, erhalte ich Too少的参数到函数 AppHttpControllersProfileController::index(), 0 Passed .

Bitte helfen Sie?

P粉404539732P粉404539732257 Tage vor261

Antworte allen(1)Ich werde antworten

  • 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);
    }
    

    Antwort
    0
  • StornierenAntwort