0

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

2 Answers 2

3

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 ]
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

Always explain your answer instead of just saying "Try this".
@GertB. You are right. I've edited my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.