I need help with passing the variable I have initialized using __construct()
to view in Laravel.
Here is my controller code
protected $profileInfo;
public function __construct(){
$this->profileInfo = Profile::with('address')->where('id', '=', '1')->get();
}
public function index(){
$this->profileInfo;
return view('admin_pages.profile', compact('profileInfo'));
}
I get an error undefined variable profileInfo
CodePudding user response:
When using compact()
the parameters used must be defined as variables:
protected $profileInfo;
public function __construct(){
$this->profileInfo = Profile::with('address')->where('id', '=', '1')->get();
}
public function index(){
$profileInfo = $this->profileInfo;
return view('admin_pages.profile', compact('profileInfo'));
}
In this case compact()
will create an array like this:
[ 'profileInfo' => $this->profileInfo ]
CodePudding user response:
compact()
looks for a variable with that name in the current symbol table and adds it to the output array such that the variable name becomes the key and the contents of the variable become the value for that key.
Instead of using compact
you can pass an array like this:
protected $profileInfo;
public function __construct(){
$this->profileInfo = Profile::with('address')->where('id', '=', '1')->get();
}
public function index(){
return view('admin_pages.profile', ['profileInfo' => $this->profileInfo]);
}