Passing data to notification in laravel - laravel

Been stumped for awhile on how to pass two variables into a notification and have that notification include an action that contains a route with a token. The use case is that my application allows users (called advisors here) to give access to other users. If the added users are not already registered, their accounts will be created and they will receive an email with a token to complete their registration.
I have the following in my AddAdvisorsController:
else {
$newadvisor = Advisor::create($data);
$newadvisor->save();
$newadvisorID = $newadvisor->id;
$newAdvisorEmail = $newadvisor->email;
//create a token
$token = Str::random(60);
//email advisor and pass $token variable to notification
$newadvisor->notify(new NewAdvisorNotification($token, $newAdvisorEmail));
I have the following in my NewAdvisorNotification:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class NewAdvisorNotification extends Notification
{
use Queueable;
public $token;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($token, $newAdvisorEmail)
{
//
$this->token = $token;
$this->newAdvisorEmail = $newAdvisorEmail;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->line('You are receiving this email because we received a new account request for your email.')
->action('Notification Action', route('new.advisor', [$this->token, $this->newAdvisorEmail]))
// ->action('Notification Action', route('advisor/new-account/{{ $token }}/{newAdvisorEmail}'))
->line('If you did not request a password reset, no further action is required.');
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
The new user is getting created properly in the database, but I get an error saying:
Missing required parameters for [Route: update.advisor] [URI: advisor/new-account/{token}/{newAdvisorEmail}]. (View: C:\xampp\htdocs\HealthHub\resources\views\auth\new-accounts\advisor-new-account.blade.php)
I have the following routes:
Route::get('/advisor/new-account/{token}/{newAdvisorEmail}', 'NewAdvisorController#showNewAccountForm')->name('new.advisor');
Route::post('/advisor/new-account/{token}/{newAdvisorEmail}', 'NewAdvisorController#updateNewAccount')->name('update.advisor');
});
I think my code is having errors with this line:
->action('Notification Action', route('new.advisor', [$this->token, $this->newAdvisorEmail]))
However, I am not sure how to fix it

You error clearly states you are missing parameters for your route. The way to specify route parameters is by name, so declare an associate array with the route parameter name as the key.
->action('Notification Action', route('new.advisor', ['token' => $this->token, 'newAdvisorEmail' => $this->newAdvisorEmail,]))

Related

Fortify - How to customise verification / password reset emails?

I'm in the process of implementing fortify into my app. I'm really confused about customising the default emails that are produced when you hit the password-reset / verifty-email routes?
I could edit them in vendor but that going to cause me an issue every time I update.
There must be a hook to provide an alternative email template.
Unfortnatly I cant find any documentation that explains how its done.
Do I need to add:
public function sendEmailVerificationNotification()
{
}
To my user model? If so how to I generate the return verificaiton URL as its not being held in the database?
Any help would be great.
Thanks!
Here is the solution in Laravel 8.
1.) Create a Notification by command
php artisan make:notification ResetPasswordNotification
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Lang;
class ResetPasswordNotification extends ResetPassword
{
use Queueable;
/**
* Create a new notification instance.
*
* #return void
*/
public $token;
public function __construct($token)
{
$this->token = $token;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
if (static::$toMailCallback) {
return call_user_func(static::$toMailCallback, $notifiable, $this->token);
}
$url = url(config('app.url') . route('password.reset', [
'token' => $this->token,
'email' => $notifiable->getEmailForPasswordReset(),
], false));
return (new MailMessage)
->view(
'emails.reset_password', ['name'=>$notifiable->name,'url' => $url]
)
->subject(Lang::get('Reset Password'));
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
2.) In the app/Models/User.php Model. Add below method.
public function sendPasswordResetNotification($token)
{
$this->notify(new ResetPasswordNotification($token));
}
3.) Now create an email template in views/emails/reset_password.blade.php
Hi {{ $name }}, Please reset your password here. Click on the below link to reset the password.
RESET
You can customize the password reset email by adding the following in FortifyServiceProvider
ResetPassword::toMailUsing(function($user, string $token) {
return (new MailMessage)
->subject('Reset Password')
->view('emails.password_reset', [
'user' => $user,
'url' => sprintf('%s/users/password_reset/%s', config('app.url'), $token)
]);
});
Create a file named resources/views/emails/password_reset.blade.php, in this file you can use $user and $url
You can enter the directory when you use fortify vendor\laravel\framework\src\Illuminate\ Notifications\resources\views\email.blade.php and overwrite the content and style of the email.
Notifications are by default in the directory vendor\laravel\framework\src\Illuminate\Auth\Notifications\VerifyEmail.php
You can change the email text lines there. Similarly reset password in ResetPassword.php

Why is the data column empty? Laravel Notifications

I am trying to set up database notification, but the data I am sending for the 'data' column isn't showing up...
My notification class:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use App\User;
use App\Admin;
class UserAddedToStudio extends Notification implements ShouldQueue
{
use Queueable;
public $user;
public $admin;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(User $user, Admin $admin)
{
$this->user = $user;
$this->admin = $admin;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail', 'database'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Welcome to '.$this->admin->name.'\'s studio')
->line('Hi '.$this->user->name.'. Your request to join '.$this->admin->name.'\'s studio has been accepted! Now you can start registering for lessons.')
// ->action('Notification Action', url('/'))
->line('Thank you for using our application!');
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toDatabase($notifiable)
{
return [
'message' => 'You have been added to the studio'
];
}
}
In my notifications table on MySQL all the columns are filled except for the data column. There I only get an empty array []. but why?? so frustrating.... :(
Here is the screenshot from my phpmyadmin.
Try to use toArray() instead of toDatabase()
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
'message' => 'You have been added to the studio'
];
}
as you use Queue you should restart the queue worker.
php artisan queue: work
Remember, queue workers, are long-lived processes and store the booted application state in memory. As a result, they will not notice changes in your code base after they have been started. So, during your deployment process, be sure to restart your queue workers. In addition, remember that any static state created or modified by your application will not be automatically reset between jobs.

How do I make the reset password url dynamic?

<?php
namespace Illuminate\Auth\Notifications;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Lang;
class ResetPassword extends Notification
{
/**
* The password reset token.
*
* #var string
*/
public $token;
/**
* The callback that should be used to create the reset password URL.
*
* #var \Closure|null
*/
public static $createUrlCallback;
/**
* The callback that should be used to build the mail message.
*
* #var \Closure|null
*/
public static $toMailCallback;
/**
* Create a notification instance.
*
* #param string $token
* #return void
*/
public function __construct($token)
{
$this->token = $token;
}
/**
* Get the notification's channels.
*
* #param mixed $notifiable
* #return array|string
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Build the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
if (static::$toMailCallback) {
return call_user_func(static::$toMailCallback, $notifiable, $this->token);
}
if (static::$createUrlCallback) {
$url = call_user_func(static::$createUrlCallback, $notifiable, $this->token);
} else {
$url = url(route('password.reset', [
'token' => $this->token,
'email' => $notifiable->getEmailForPasswordReset(),
], false));
}
return (new MailMessage)
->subject(Lang::get('Reset Password Notification'))
->line(Lang::get('You are receiving this email because we received a password reset request for your account.'))
->action(Lang::get('Reset Password'), $url)
->line(Lang::get('This password reset link will expire in :count minutes.', ['count' => config('auth.passwords.'.config('auth.defaults.passwords').'.expire')]))
->line(Lang::get('If you did not request a password reset, no further action is required.'));
}
/**
* Set a callback that should be used when creating the reset password button URL.
*
* #param \Closure $callback
* #return void
*/
public static function createUrlUsing($callback)
{
static::$createUrlCallback = $callback;
}
/**
* Set a callback that should be used when building the notification mail message.
*
* #param \Closure $callback
* #return void
*/
public static function toMailUsing($callback)
{
static::$toMailCallback = $callback;
}
}
Hi, I am using Laravel 7.6.2.
I keep on getting an error. I am trying to make a multiauth login system, and I am testing the password reset routes. The problem is that when I access the admin forgot password page, the email that is sent actually contains a link to the user password reset page, not the admin password reset page.
So route('password.reset' should actually be route('admin.password.reset' for the admin request. But I really have no clue how to make this URL dynamic.... Help please!!
Another option is to add this to the boot method in your AppServiceProvider:
ResetPassword::createUrlUsing(function ($notifiable, $token) {
return "http://www.my-spa.co/password/reset/{$token}";
});
I use Laravel as an API and needed this to generate a link to my single page application url.
The ResetPassword notification provided by the Laravel framework allows custom URLs out of the box. The method createUrlUsing lets you provide a function that will generate the URL in the output email.
Example in the User model class:
// Import the ResetPassword class from the framework
use Illuminate\Auth\Notifications\ResetPassword;
class User extends Authenticatable {
// ... the rest of your implementation
// The customization of the email happens here
/**
* Send the password reset notification.
*
* #param string $token
* #return void
*/
public function sendPasswordResetNotification($token) {
// The trick is first to instantiate the notification itself
$notification = new ResetPassword($token);
// Then use the createUrlUsing method
$notification->createUrlUsing(function ($token) {
return 'http://acustomurl.lol';
});
// Then you pass the notification
$this->notify($notification);
}
}
I don't know if it's completely off topic but that was what I was looking for 😅
I have done as following:
In Admin user class override sendPasswordResetNotification method:
/**
* Send the password reset notification.
*
* #param string $token
* #return void
*/
public function sendPasswordResetNotification($token)
{
$this->notify(new AdminMailResetPasswordToken($token));
}
In AdminMailResetPasswordToken extends default Laravel ResetPassword notification class:
namespace App\Notifications\Admin\Auth;
use Illuminate\Auth\Notifications\ResetPassword;
class AdminMailResetPasswordToken extends ResetPassword
{
public static $createUrlCallback = [self::class, 'createActionUrl'];
public static function createActionUrl($notifiable, $token)
{
return url(route('admins.password.reset', [
'token' => $token,
'email' => $notifiable->getEmailForPasswordReset(),
], false));
}
}
ResetPassword::createUrlUsing(function ($notifiable, $token) {
$route = Request::is('admin/password/reset')
? 'admin.password.reset'
: 'password.reset';
return url(route($route, [
'token' => $token,
'email' => $notifiable->getEmailForPasswordReset(),
], false));
});`
Here what I did in the User model
use Illuminate\Auth\Notifications\ResetPassword;
/**
* Override the mail body for reset password notification mail.
*/
public function sendPasswordResetNotification($token)
{
ResetPassword::createUrlUsing(function ($user, string $token) {
return 'https://example.com/reset-password?token='.$token;
});
$this->notify(new ResetPassword($token));
}

Laravel 5.8 on demand notification error Call to a member function create() on null

When I do this, the user receives email without error:
Notification::send($user, new TicketNotification($details));
But, when I do this, the user also receives an email, but with an error in the screenshot below
Notification::route('mail', 'email_of_non-db_user')->notify(new TicketNotification($details));
Error: Call to a member function create() on null
Do have any idea why? How can I avoid this error?
I have to use On Demand Notification because I need to send a notification to someone who is not stored as a "user".
i think try this one
in TicketNotification update via method with this for only send to mail.
But u r also saved notification into database..
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail'];
}
Thanks Jignesh, your answer works.
Sorry Thamer, I should have posted the whole code from the beginning.
Before, it was :
return ['mail','database'];
Now only :
return ['mail'];
Then, there is no error anymore.
Here my TicketNotification that made the error:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class TicketNotification extends Notification
{
use Queueable;
private $details;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($details)
{
$this->details = $details;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail','database'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->subject($this->details['subject'])
->greeting($this->details['title'])
->line($this->details['body'])
->line($this->details['links'])
;
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toDatabase($notifiable)
{
return [
'order_id' => $this->details['order_id']
];
}
}
Add this to your via method to use the same Notification for all your issues:
public function via($notifiable)
{
$availableChannels = [
'mail' => 'mail',
'database' => 'database',
'slack' => 'slack',
'telegram' => TelegramChannel::class
];
$channels = [];
foreach ($availableChannels AS $channel => $driver) {
if ($notifiable->routeNotificationFor($channel)) {
$channels[] = $driver;
}
}
return $channels;
}
You can now use On-Demand Notifications or fire the notificaton on users, without having to make multiple Notifications for each Channel or ON-DEMANDS etc...

Laravel undefined variable in Notification

I'm experimenting with laravel and I came across this article.
I followed it exactly but for some reason when sending the mail in the Notification class, he can't find the $user variable I declared in the constructor. When printing it in the constructor it works so the user object is passed correctly, but when I want to access it in the toMail method, it's inexisting for some reason. Anyone know why & how to fix this?
<?php
namespace App\Notifications;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class UserRegisteredSuccessfully extends Notification
{
use Queueable;
/**
* #var User
*/
protected $user;
/**
* Create a new notification instance.
*
* #param User $user
*/
public function __construct(User $user)
{
$this->$user = $user;
// printing here works
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
// ERROR HERE (Undefined variable: user)
$user = $this->$user;
return (new MailMessage)
->subject('Succesfully created new account')
->greeting(sprintf('Hello %s', $user->username))
->line('You have successfully registered to our system. Please activate your account.')
->action('Click here', route('activate.user', $user->activation_code))
->line('Thank you for using our application!');
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
Register Method:
/**
* Register new user
*
* #param Request $request
* #return User
*/
protected function register(Request $request)
{
$validatedData = $request->validate([
'username' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
try {
$validatedData['password'] = Hash::make(array_get($validatedData, 'password'));
$validatedData['activation_code'] = str_random(30).time();
$user = app(User::class)->create($validatedData);
} catch(\Exception $ex) {
logger()->error($ex);
return redirect()->back()->with('message', 'Unable to create new user.');
}
$user->notify(new UserRegisteredSuccessfully($user));
return redirect()->back()->with('message', 'Successfully created a new account. Please check your email and activate your account.');
}
Thanks in Advance!
You made 2 typos:
In your constructor:
$this->$user = $user;
Should be:
$this->user = $user;
And in the toMail() method:
$user = $this->$user;
Should be:
$user = $this->user;
The reason it is not working, is because you are currently using the value of $user as the variable name, and you are not assigning the value of the User object to $this->user.

Resources