I wish to initialize a particular variable and reuse it within the class without needing to rewrite the entire code again and again within the class.
$profileInfo = Profile::with('address')->where('id', '=', '1')->get();
The variable above is what 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 I get Too few arguments to function App\Http\Controllers\ProfileController::index(), 0 passed
in the display when I load the blade view in the browser.
Please any help?
CodePudding user response:
You're having trouble because you are mixing concepts. Dependency Injection, Local instance variables, and possibly route model binding or route variable binding.
Dependency Injection is asking Laravel to provide an instance of a class for you. In cases where Laravel is loading something, it typically tries to use DI to fill the unknowns. In the case of your constructor, you're asking Laravel to provide the constructor with a fresh instance of the Profile
class under the variable name $profileInfo
. You do not end up using this variable in the constructor, so there is no point to requesting it here.
Next (still in the constructor) you set up and assign the local variable profileInfo
to the controller class instance.
Moving on, when the route tries to trigger the index
method there is a variable requirement of $profileInfo
. Laravel doesn't know what this is here and it doesn't match anything from the route (See Route Model Binding in the docs). Because of this you get the "Too few arguments" message.
If this variable was not present, you should have the profileInfo
you set up earlier.
If you want to keep the local variable, you can do something like 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 Profile, it seems like we should ask a 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);
}