How to initialize a given function in Laravel controller
P粉404539732
P粉404539732 2024-01-10 16:51:22
0
1
312

I want to initialize a specific variable and reuse it in the class without having to rewrite the entire code again and again in the class.

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

The variables above are the ones I want to reuse.

I tried using constructor

protected $profileInfo;

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

But when I load the blade view in the browser, I get Too few parameters to the function App\Http\Controllers\ProfileController::index(), 0 Passed .

Please help?

P粉404539732
P粉404539732

reply all(1)
P粉627027031

You are in trouble because you are confusing concepts. Dependency injection, local instance variables, and possibly route model binding or route variable binding.

Dependency injection requires Laravel to provide you with an instance of a class. In situations where Laravel loads something, it will usually try to fill in unknowns using DI. For the constructor, you ask Laravel to provide the constructor with a new instance of the Profile class under the variable name $profileInfo. You won't end up using this variable in the constructor, so there's no need to request it here.

Next (still in the constructor) set the local variable profileInfo and assign it to the controller class instance.

Continuing, when the route attempts to trigger the index method, there is a variable requirement for $profileInfo. Laravel has no idea what this is, and it doesn't match anything in the route (see Route Model Binding in the documentation). Therefore, you get the "Too few parameters" message. If this variable does not exist, you should have the profileInfo set previously.

If you want to keep local variables, you can do this:

protected $profileInfo;

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

Here is another suggestion for you to consider...

Since this is called a profile, it seems like we should ask the user model for the appropriate profile record.

// 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);
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template