Laravel Mail view not returning passed data - laravel

I am trying to send email using Laravel default Mail facade:-
Mail::to($user->email)->send(New NotifyUserExpiring($diff,$Sub->user));
In Mail\NotifyUserExpiring :-
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class NotifyUserExpiring extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
protected $user;
protected $diff;
public function __construct($diff,$user)
{
$this->user = $user;
$this->diff = $diff;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('web.mail.NotifyUserExpiring')->with('user',$this->user)->with('diff',$this->diff);
}
}
And in web.mail.NotifyUserExpiring View file i am using the blade way of printing variable :-
Hello {{ $user->first_name }}
Message Here
When i check my mail inbox , i am reciving email with exact {{ $user->first_name }}
Hello {{ $user->first_name }}
Message Here
I am expecting that when i insert {{ $user->first_name }} in mail view file , it should return user first name.
<div>
Hello {{ $user->first_name }}
Message body test
</div>

Make sure your mail view file name is suffixed as .blade.php so that it goes through the Blade rendering engine.

The with() method you can pass as an array, see the documentation:
return $this->view('web.mail.NotifyUserExpiring')->with([
'user',$this->user,
'diff',$this->diff
]);

Related

"Undefined variable $token",

PasswordResetController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Response;
use App\Http\Requests\PasswordResetRequest;
use Illuminate\Support\Str;
use App\Models\PasswordReset;
use App\Models\User;
use Illuminate\Support\Facades\Mail;
use App\Mail\PasswordResetMail;
class PasswordResetController extends Controller
{
public function reset_email(PasswordResetRequest $request){
$validated = $request->validated();
$token=Str::random(60);
PasswordReset::create([
'email'=>$validated['email'],
'token'=>$token,
]);
$user=User::where('email',$validated['email'])->get();
$mail=Mail::to($validated['email'])->send(new PasswordResetMail($user),['token'=>$token]);
if($mail){
return response([
'message'=>"Password reset email sent suceesfully",
],Response::HTTP_OK);
}
return response([
'message'=>"Failed to send passport reset email",
],Response::HTTP_UNAUTHORIZED);
}
}
PasswordResetMail.php
<?php
namespace App\Mail;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class PasswordResetMail extends Mailable
{
use Queueable, SerializesModels;
public $user;
/**
* The order instance.
*
*/
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($user)
{
$this->user=$user;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('test');
}
}
test.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
#foreach($user as $u)
{{ $u->name }}
#endforeach
{{ $token }}
</body>
</html>
I am trying to send a password reset link into the mail so, whenever the user types their email into the email reset link page and presses send email reset link button an email will be sent along with the token. Here, I am trying to send a token into the email by writing above code but it is showing an undefined variable error on the test.blade.php page. What am I doing wrong I have no idea any suggestions, will be highly appreciated.
PasswordResetMail.php construct should be like this
public function __construct($user,$token)
{
$this->user=$user;
$this->token=$token;
}
and don't forget to add this before construct:
public $token;
and in PasswordResetController class change mail variable exemple :
$mail=Mail::to($validated['email'])->send(new PasswordResetMail($user,$token));
i hope it was useful

{{ auth()->user()->email }} / {{ Auth::user()->email }} not working in x-component

php artisan make:component Navbar, created:
App\View\Components\Navbar.php
app\resources\views\components\navbar.blade.php
Placing {{ auth()->user()->email }} or {{ Auth::user()->email }} in the blade file, gave this error:
Trying to get property 'email' of non-object.
Tried to fix this by changing my App\View\Components\Navbar.php to:
<?php
namespace App\View\Components;
use Illuminate\View\Component;
class Navbar extends Component
{
public $email;
/**
* Create a new component instance.
*
* #return void
*/
public function __construct($email = null)
{
$this->email = 'info#example.com';
}
/**
* Get the view / contents that represent the component.
*
* #return \Illuminate\Contracts\View\View|\Closure|string
*/
public function render()
{
return view('components.navbar');
}
}
And added {{ $email }} to my blade file and it worked.
However, I want to display the e-mail address from the authenticated user, so I changed App\View\Components\Navbar.php to:
<?php
namespace App\View\Components;
use Illuminate\View\Component;
use Illuminate\Support\Facades\Auth;
class Navbar extends Component
{
public $email;
/**
* Create a new component instance.
*
* #return void
*/
public function __construct($email = null)
{
$this->email = Auth::user()->email;
}
/**
* Get the view / contents that represent the component.
*
* #return \Illuminate\Contracts\View\View|\Closure|string
*/
public function render()
{
return view('components.navbar');
}
}
And I got the same error again.
The error you're having because the user is not authenticated. Maybe add a check before calling the component in the blade file, wrap the component between #auth directive. Something like this
#auth
<x-navbar></x-navbar>
#endauth

laravel 8 markdown email image not showing

I'm dispatching a markdown email using the Laravel's mailable class.
Here's the following code for the mailable.
<?php
namespace App\Mail;
use App\traits\Mail\RecordMailTrait;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Laravel\Spark\Invitation;
class ExistingUserCompanyInviteMail extends Mailable
{
use Queueable, SerializesModels, RecordMailTrait;
/**
* Create a new message instance.
*
* #return void
*/
protected $invite;
public $inviter;
public $view = 'email.invitation-to-current-user';
public function __construct(Invitation $invite, User $inviter)
{
$this->invite = $invite;
$this->inviter = $inviter;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$invitation = $this->invite;
$view = $this->view;
$to = $this->to[0]['address'];
$sent_by_email = $this->inviter->email;
$this->withSwiftMessage(function ($message) use($invitation, $view, $to, $sent_by_email){
$message->view = $view;
$message->sent_to_email = $to;
$message->sent_by_email = $sent_by_email;
$message->mailable_type = Invitation::class;
$message->mailable_id = $invitation->id;
});
return $this->markdown($this->view,['invitation' => $this->invite, 'inviter' => $this->inviter, 'entity' => $this->invite->team->name, 'url' => url('/home/invitations')])->subject("Invitation");
}
}
I get the email in my inbox, with the correct text and styling, however not the image, it doesn't load as it should.
Here's the code for the HTML:
<tr>
<td class="header">
<a href="{{ $url }}" style="display: inline-block;">
<img src="{{ asset('/img/logo.svg')}}" class="logo" alt="logo1">
</a>
</td>
</tr>
This is the URL I get from the image in the sent email:
https://ci3.googleusercontent.com/proxy/8oh80_LJVyfK50ZObX23alnA8vhDzf3vXWJC_kHVgccnfzs-zSher-TbH9fO4RcDWjTQ5s8c_q3V6qc=s0-d-e1-ft#http://core-hosp.test/img/logo.svg
logo does not show (image of email)

Laravel Email Verification Template Location

I have been reading from the documentation about the new feature of laravel the email verification. Where can I locate the email template that is sent to the user? It does not show here: https://laravel.com/docs/5.7/verification#after-verifying-emails
Laravel uses this method of VerifyEmail notification class for send email:
public function toMail($notifiable)
{
if (static::$toMailCallback) {
return call_user_func(static::$toMailCallback, $notifiable);
}
return (new MailMessage)
->subject(Lang::getFromJson('Verify Email Address'))
->line(Lang::getFromJson('Please click the button below to verify your email address.'))
->action(
Lang::getFromJson('Verify Email Address'),
$this->verificationUrl($notifiable)
)
->line(Lang::getFromJson('If you did not create an account, no further action is required.'));
}
Method in source code.
If you wanna use your own Email template, you can extend Base Notification Class.
1) Create in app/Notifications/ file VerifyEmail.php
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Lang;
use Illuminate\Auth\Notifications\VerifyEmail as VerifyEmailBase;
class VerifyEmail extends VerifyEmailBase
{
// use Queueable;
// change as you want
public function toMail($notifiable)
{
if (static::$toMailCallback) {
return call_user_func(static::$toMailCallback, $notifiable);
}
return (new MailMessage)
->subject(Lang::getFromJson('Verify Email Address'))
->line(Lang::getFromJson('Please click the button below to verify your email address.'))
->action(
Lang::getFromJson('Verify Email Address'),
$this->verificationUrl($notifiable)
)
->line(Lang::getFromJson('If you did not create an account, no further action is required.'));
}
}
2) Add to User model:
use App\Notifications\VerifyEmail;
and
/**
* Send the email verification notification.
*
* #return void
*/
public function sendEmailVerificationNotification()
{
$this->notify(new VerifyEmail); // my notification
}
Also if you need blade template:
laravel will generate all of the necessary email verification views
when the make:auth command is executed. This view is placed in
resources/views/auth/verify.blade.php. You are free to customize
this view as needed for your application.
Source.
Answer in comment already. Sent by the toMail() method.
vendor\laravel\framework\src\Illuminate\Auth\Notifications\VerifyEmail::toMail();
For template structure and appearance; take a look at this locations also and you can also publish to modify the template:
\vendor\laravel\framework\src\Illuminate\Notifications\resources\views\email.blade.php
\vendor\laravel\framework\src\Illuminate\Mail\resources\views\
To publish those locations:
php artisan vendor:publish --tag=laravel-notifications
php artisan vendor:publish --tag=laravel-mail
After running this command, the mail notification templates will be located in the resources/views/vendor directory.
Colors and style are controlled by the CSS file in resources/views/vendor/mail/html/themes/default.css
Also, if you want to translate standard mail VerifyEmail (or other where use Lang::fromJson(...)), you need create new json file in resources/lang/ and name it ru.json, for example.
It may contain (resources/lang/ru.json) text below and must be valid.
{
"Verify Email Address" : "Подтверждение email адреса"
}
Actually they do not use any blade or template files. They create notifications and write code for it in notifications.
Look I do that very easy
do the following steps :
In Route File
Auth::routes(['verify' => true]);
In AppServiceProvider.php File
namespace App\Providers;
use App\Mail\EmailVerification;
use Illuminate\Support\ServiceProvider;
use View;
use URL;
use Carbon\Carbon;
use Config;
use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Notifications\Messages\MailMessage;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
// Override the email notification for verifying email
VerifyEmail::toMailUsing(function ($notifiable){
$verifyUrl = URL::temporarySignedRoute('verification.verify',
\Illuminate\Support\Carbon::now()->addMinutes(\Illuminate\Support\Facades
\Config::get('auth.verification.expire', 60)),
[
'id' => $notifiable->getKey(),
'hash' => sha1($notifiable->getEmailForVerification()),
]
);
return new EmailVerification($verifyUrl, $notifiable);
});
}
}
Now Create EmailVerification With Markdown
php artisan make:mail EmailVerification --markdown=emails.verify-email
Edit The EmailVerrification as you want and the blade file
class EmailVerification extends Mailable
{
use Queueable, SerializesModels;
public $verifyUrl;
protected $user;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($url,$user)
{
$this->verifyUrl = $url;
$this->user = $user;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$address = 'mymail#gmail.com';
$name = 'Name';
$subject = 'verify Email';
return $this->to($this->user)->subject($subject)->from($address, $name)->
markdown('emails.verify',['url' => $this->verifyUrl,'user' => $this->user]);
}
}
in the blade file change the design as you want and use verifyUrl to display the verification link and $user to display user information
thanks, happy coding :)
vendor\laravel\framework\src\Illuminate\Mail\resources\views\html
You will find the Laravel default email template in this file location.
If a notification supports being sent as an email, you should define a toMail method on the notification class. This method will receive a $notifiable entity and should return a Illuminate\Notifications\Messages\MailMessage instance. Mail messages may contain lines of text as well as a "call to action".
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
$url = url('/invoice/'.$this->invoice->id);
return (new MailMessage)
->greeting('Hello!')
->line('One of your invoices has been paid!')
->action('View Invoice', $url)
->line('Thank you for using our application!');
}
You can use the laravel e-mail builder as documented here: https://laravel.com/docs/5.8/notifications#mail-notifications. Laravel will take care of the e-mail view.

Laravel - Pass custom data to email view

Following on from a previous question, I have an email controller set up to correctly pass user data to the view. I am now trying to modify it so I can pass some custom data instead. My controller looks like this...
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class Welcome extends Mailable
{
use Queueable, SerializesModels;
public $email_data;
public function __construct($email_data)
{
$this->email_data = $email_data;
}
public function build()
{
return $this->view('emails.welcome')->with(['email_data' => $this->email_data]);
}
}
And I am sending the email like this...
/* Create Data Array For Email */
$email_data = array(
'first_name'=>'John',
'last_name'=>'Doe',
'email'=>'john#doe.com',
'password'=>'temp',
);
/* Send Email */
Mail::to($user->email)->send(new Welcome($email_data));
Is this correct? When I try using this method it does not seem to be passing the data through to the email template. How can I then access this data within the view?
Have you tried this way ?
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class Welcome extends Mailable
{
use Queueable, SerializesModels;
public $data;
public function __construct($data)
{
$this->data = $data;
}
public function build()
{
return $this->view('emails.welcome')->with('data', $this->data);
}
}
and then in your controller from where you are creating your array of data,
$data = [
'first_name'=>'John',
'last_name'=>'Doe',
'email'=>'john#doe.com',
'password'=>'temp'
];
\Mail::to($user->email)->send(new Welcome($data));
Please make sure that you add
use Mail;
use App\Mail\Welcome;
in your controller.
You can access the data in your view like this
{{ $data['first_name'] }}
{{ $data['last_name'] }}
{{ $data['email'] }}
{{ $data['password'] }}
OR
You can also try Markdown mails for this
You don't need this part ->with(['email_data' => $this->email_data]) because if the property is public you can access it in the view.
And you are passing an array so you have to access the values like this :
$email_data['email'] // ...
There are two ways to pass data through the view. First, any public defenses defined in the mailable class pass automatically through the view.
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class Welcome extends Mailable
{
use Queueable, SerializesModels;
public $firstName;
public $lastName;
public $email;
public $password;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($firstName, $lastName, $email, $password)
{
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->email = $email;
$this->password = $password;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('emails.orders');
}
}
In Blade view
<div>
First Name: {{ $firstName }}
Last Name: {{ $lastName }}
Email: {{ $email }}
Password: {{ $password }}
</div>
For variables with protected and private properties, it is possible to pass data through a view with the with method
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class Welcome extends Mailable
{
use Queueable, SerializesModels;
protected $firstName;
protected $lastName;
protected $email;
protected $password;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($firstName, $lastName, $email, $password)
{
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->email = $email;
$this->password = $password;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('emails.orders')->with([
'first_name'=> $this->firstName,
......
]);
}
}
In Blade view
<div>
First Name: {{ $firstName }}
Last Name: {{ $lastName }}
Email: {{ $email }}
Password: {{ $password }}
</div>

Resources