I want to send email with some information. That's why I use compact()
function within view()
function. But I got an error 'undefined variable':
public $message_to_send="";
public $first_name_to_send="";
public function __construct($first_name,$message) {
$this->message_to_send=$message;
$this->first_name_to_send=$first_name;
}
public function build(){
return $this->view('email/contactmessageemail',compact('message_to_send','first_name_to_send'));
}
The error message is:
compact(): Undefined variable: message_to_send
try to edit it to
view('email.contactmessageemail',[
'message_to_send' => $this->message_to_send,
'first_name_to_send' => $this->first_name_to_send
]);
compact
didn't work in your case because the variables that you want to pass in is not locally defined in the method scope it is declared as a public property
This was a breaking changed introduced in PHP 7.3 with compact()
. Previously, you could send through undefined variables with compact()
, but now it flags as an error.
compact()
is still a fantastic method - but you will need to define the variables within the method that you are using it. To keep code clean and readable, I suggest you define the variables and then pass using compact()
as you had originally intended.
So you can fix using the original code like this:
public function build(){
$message_to_send = $this->message_to_send;
$first_name_to_send = $this->first_name_to_send;
return view('email.contactmessageemail',compact('message_to_send','first_name_to_send'));
}
Note I removed $this
from the view call.
You can also always pass the variables right into the build()
method - which is sort of the norm - then you don't have to define within the method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.