Undefined variable inside Laravel view when using Mail - laravel-5

While trying to send verification email using Laravel 5.2, I get an error:
Undefined variable: confirmation_code (View:
C:\xampp\htdocs\laravel\resources\views\email\verify.blade.php)
My code looks like this:
Controller.php:
public function postSignup(Request $request){
$this->validate($request,[
'email'=>'required|unique:users|email',
'name'=>'required|max:50|min:3',
'password'=>'required|min:6',
'con-password'=>'required|same:password',
]);
$confirmation_code=['code'=>str_random(20)];
$name = $request->input('name');
Mail::send('email.verify',$confirmation_code,function($message)
use($request,$name){
$message->to($request->input('email'),$name)
->subject('Verify Your Email Address');
});
User::create([
'email'=>$request->input('email'),
'name'=>$request->input('name'),
'password'=>bcrypt($request->input('password'))
]);
return redirect()->back()->with('info','Congratulation you have been successfully registered.Please check your email for verification');
}
Mail.verify.blade.php:
<h2>Verify Your Email Address</h2>
<div>
Thanks for creating an account with the verification demo app.
Please follow the link below to verify your email address
{{ URL::to('register/verify/'.$confirmation_code) }}.<br/>
</div>
</body>

Try this:
Mail::send('email.verify', compact('confirmation_code'), function ($message) use($request, $name) {
$message->to($request->input('email'),$name)
->subject('Verify Your Email Address');
});
The reason why it fails is that Laravel views accept an associative array as their data, so that it can turn them into variables using keys as variables names and match them to their corresponding values.
What compact does is turn your variable into an associative array, with the name of the variable as its key (sort of the opposite of what the Laravel view will do).

Related

Why giving undefined variable in sending Email attachment in Laravel?

I can't pass any variable to Email body from Controller. I have searched many solutions but no is matching with me.
I am using Mailable. But it is empty. I am not sure it is creating problem or not.
public function __construct(){}
public function build(){}
I have tested with dummy Email without passing variable. Email is sending successfully. So, I think there is no problem with configuration.
Function in controller:
public function mail()
{
$info = Invoice::find(65)->first();
// 65 is giving me value. I have checked with dd()
$data = [
'invoice' => $info->invoiceNumber
];
Mail::send(['text'=>'invoice.test'], $data, function($message) use($data){
$pdf = PDF::loadView('invoice.test');
$message->to('example#gmail.com','John Smith')->subject('Send Mail from Laravel');
$message->from('from#gmail.com','The Sender');
$message->attachData($pdf->output(), 'Invoice.pdf');
});
return 'Email was sent';
}
test.blade.php
<h1>It is working!! {{ $invoice }}</h1>
Data sending style is followed by:
Laravel Mail::send how to pass data to mail View
Try adding the $data with the PDF view:
$pdf = PDF::loadView('invoice.test', $data);
But if you want to add an email body content different with the PDF content, try this:
Mail::send([], $data, function($message) use($data){
$pdf = PDF::loadView('invoice.test', $data);
$message->to('example#gmail.com','John Smith')->subject('Send Mail from Laravel');
$message->from('from#gmail.com','The Sender');
$message->setBody('sample mail content');
$message->attachData($pdf->output(), 'Invoice.pdf');
});

Laravel 5.5 - Send Email - Can't Get Property On Non-Object

I am trying to send email from a Laravel 5.5 controller like this...
$user = User::find(1)->toArray();
Mail::send('emails.invite', $user, function($message) use ($user) {
$message->to($user->email);
$message->from('me#example.com');
$message->subject('Test Subject');
});
This fails with the error...
"message": "Trying to get property of non-object",
If I echo the array into the subject I can see that I do have the correct $user available to me, but for some reason it doesn't like it when I try and extract $user->email
Anyone any ideas?
You're calling ->toArray() on the User object and so it is no longer an object!
$user = User::find(1); // Assuming you are already protecting yourself from potentially not finding a user
$viewData = $user->toArray(); // Or better still don't expose the underlying structure
Mail::send('emails.invite', $viewData, function($message) use ($user) {
$message->to($user->email);
$message->from('me#example.com');
$message->subject('Test Subject');
});
Your $user is type ofarray not object as you expected, because of toArray() called on returned model. Either change that line and remove said toArray() to keep it unchanged object, or make this line:
$message->to($user->email);
look more like:
$message->to($user['email']);
with proper array element reference.

How to change From Name in Laravel Mail Notification

This is the problem:
The name associated with the email shows up as "Example"
In config/mail.php
set from property as:
'from' => ['address' => 'someemail#example.com', 'name' => 'Firstname Lastname']
Here, address should be the one that you want to display in from email and name should be the one what you want to display in from name.
P.S. This will be a default email setting for each email you send.
If you need to use the Name as a variable through code, you can also call the function from() as follows (copying from Brad Ahrens answer below which I think is good to mention here):
return $this
->from($address = 'noreply#example.com', $name = 'Sender name')
->subject('Here is my subject')
->view('emails.view');
You can use
Mail::send('emails.welcome', $data, function($message)
{
$message->from('us#example.com', 'Laravel');
$message->to('foo#example.com')->cc('bar#example.com');
});
Reference - https://laravel.com/docs/5.0/mail
A better way would be to add the variable names and values in the .env file.
Example:
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=example#example.com
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls
MAIL_FROM_NAME="My Name"
MAIL_FROM_ADDRESS=support#example.com
Notice the last two lines. Those will correlate with the from name and from email fields within the Email that is sent.
In the case of google SMTP, the from address won't change even if you give this in the mail class.
This is due to google mail's policy, and not a Laravel issue.
Thought I will share it here.
For anyone who is using Laravel 5.8 and landed on this question, give this a shot, it worked for me:
Within the build function of the mail itself (not the view, but the mail):
public function build()
{
return $this
->from($address = 'noreply#example.com', $name = 'Sender name')
->subject('Here is my subject')
->view('emails.welcome');
}
Happy coding :)
If you want global 'from name' and 'from email',
Create these 2 keys in .env file
MAIL_FROM_NAME="global from name"
MAIL_FROM_ADDRESS=support#example.com
And remove 'from' on the controller. or PHP code if you declare manually.
now it access from name and from email.
config\mail.php
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'info#example.com'),
'name' => env('MAIL_FROM_NAME', 'write name if not found in env'),
],
ON my controller.
$conUsBody = '';
$conUsBody .= '<h2 class="text-center">Hello Admin,</h2>
<b><p> '.trim($request->name).' Want some assesment</p></b>
<p>Here are the details:</p>
<p>Name: '.trim($request->name).'</p>
<p>Email: '.trim($request->email).'</p>
<p>Subject: '.trim($request->subject).'</p>';
$contactContent = array('contactusbody' => $conUsBody);
Mail::send(['html' => 'emails.mail'], $contactContent,
function($message) use ($mailData)
{
$message->to('my.personal.email#example.com', 'Admin')->subject($mailData['subject']);
$message->attach($mailData['attachfilepath']);
});
return back()->with('success', 'Thanks for contacting us!');
}
My blade template.
<body>
{!! $contactusbody !!}
</body>
I think that you have an error in your fragment of code. You have
from(config('app.senders.info'), 'My Full Name')
so config('app.senders.info') returns array.
Method from should have two arguments: first is string contains address and second is string with name of sender. So you should change this to
from(config('app.senders.info.address'), config('app.senders.info.name'))

Get recipient name on view in laravel mail

I have a set of recipients. I am able to send mail to all of them. But how to get their name on the view. To be specific how to get $user value in my view(emails.test).
Mail::send('emails.test', ['data' => $data], function ($message) use ($data) {
foreach($data['users'] as $user) {
$message->to($user->email, $name = $user->firstName . ' ' . $user->lastName);
}
$message->subject('test');
});
Is there any way to access $user value in my view? I can access $data in my view. $data['users'] is an array of users. I need particular/current User's name in the view.
My view(emails.test)
<div>Dear {{$user->firstName}},</div>
How are you?....
But user is undefined here.
Thanks in advance.
Debabrata
from the docs
The send method accepts three arguments. First, the name of a view
that contains the e-mail message. Secondly, an array of data you wish
to pass to the view. Lastly, a Closure callback which receives a
message instance, allowing you to customize the recipients, subject,
and other aspects of the mail message
as you can see the second arguments its the data you send to the view
so in your view you can use the $data array just like you did inside the closure:
#foreach($data['users'] as $user) {
{{$user->username}}
}

When i am trying to send mail from contactUS form getting this error using swiftmailer in Laravel 5.2

when i am trying to send Mail through Contact Us Form receiving this Error
"Address in mailbox given [] does not comply with RFC 2822, 3.6.2."
I try search to find solution but I cannot find one. I edited config/mail.php
public function sendContactInfo(ContactMeRequest $request)
{
$data = $request->only('name', 'email');
$emailto="******#gmail.com";
$data['messageLines'] = explode("\n", $request->get('message'));
Mail::send('publicPages.contactus', $data, function ($message) use ($emailto) {
$message->subject('Contact Us Form: ')
->to(config('blog.contact_email'))
->replyTo($data['email']);
});
return back()
->withSuccess("Thank you for your message. It has been sent.");
}
with configuration file
i am following this tutorial
Laravel Send Mail
use $data['email']
Mail::send('publicPages.contactus', $data, function ($message) use ($emailto,$data['email']) {
$message->subject('Contact Us Form: ')
->to(config('blog.contact_email'))
->replyTo($data['email']);
});

Resources