Laravel 5.3 How to show Username in Notifications Email - laravel

I am trying to add the user's first name in the notification emails. At the moment, Laravel notification emails starts like:
Hello,
And I want to change it to:
Hello Donald,
Right now, I have a set-up like this. This example is for a Password Reset Notification email:
User Model:
public function sendPasswordResetNotification($token)
{
$this->notify(new PasswordReset($token));
}
App\Notifications\PasswordReset:
class PasswordReset extends Notification
{
use Queueable;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* 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('The introduction to the notification.')
->action('Notification Action', 'https://laravel.com')
->line('Thank you for using our application!');
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
Is the User Model automatically binded with the Notification Class? How can I add the username in the view?

The $notifiable variable passed to toMail() is User model.
Call to needed User model attribute, easy:
public function toMail($notifiable)
{
return (new MailMessage)
->greeting('Hello '. $notifiable->username)
->line('The introduction to the notification.')
->action('Notification Action', 'https://laravel.com')
->line('Thank you for using our application!');
}

Try this:
User Model:
public function sendPasswordResetNotification($token) {
return $this->notify(new PasswordReset($token, $this->username));
}
App\Notifications\PasswordReset:
class PasswordReset extends Notification
{
use Queueable;
public $username;
public function __construct($token, $username)
{
$this->username = $username;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->greeting('Hello '.$this->username.',')
->line('The introduction to the notification.')
->action('Notification Action', 'https://laravel.com')
->line('Thank you for using our application!');
}
}

You have to edit toMail function in App\Notifications\PasswordReset to set greeting as you want.
public function toMail($notifiable) {
return (new MailMessage)
->greeting('Hello '. $this->username)
->line('The introduction to the notification.')
->action('Notification Action', 'https://laravel.com')
->line('Thank you for using our application!');
}
Update
To set $username, have to define a variable & setter method in App\Notifications\PasswordReset.
protected $username = null;
public function setName($name) {
$this->username = $name;
}
When you initialize App\Notifications\PasswordReset, you can set the name.
In User model update the function as below.
public function sendPasswordResetNotification($token) {
$resetNotification = new ResetPasswordNotification($token);
$resetNotification->setName($this->name);
$this->notify($resetNotification);
}

Related

Laravel mailJob not showing up in telescope

I send email with MailJob class. But i dont see any job in telescope jobs section. How can i fix that?
Here is my LoginListener class which i send email when user login
public function handle(Login $event)
{
//return dd($event->user->email);
dispatch(new SendEmailJob($event->user->email,'Xoşgəldiniz','Salam .' .$event->user->name .'xoşgəldiniz....'))->onQueue('mails');;
}
Here is my my WelcomeEmail mail class
public function __construct($title, $content)
{
$this->title = $title;
$this->content = $content;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('email.welcome');
}
}

Laravel Echo.js not receiving notification from pusher no log message

I followed up some tutorials about echo and pusher. I configured all the project as necessary but object notifications not appear at browser. I uncoment the line
<?php
namespace App\Notifications;
use App\Models\Admin;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\BroadcastMessage;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class RegisterNewNotification extends Notification implements ShouldBroadcast
{
use Queueable;
/**
* Create a new notification instance.
*
* #return void
*/
public $message;
public function __construct($message)
{
$this->message = $message;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['broadcast'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->line('The introduction to the notification.')
->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' => $this->message,
];
}
public function toBroadcast($notifiable)
{
return new BroadcastMessage([
'message' => $this->message,
]);
}
public function toArray($notifiable)
{
return [
//
];
}
}
Broadcast::channel('App.Models.Admin.{adminId}', function ($admin, $adminId) {
return $admin->id === $adminId;
});
Route::get('noti',function(){
$user = Admin::first();
$user->notify(new RegisterNewNotification("Hello"));
});
<script type="module">
Echo.private('App.Models.Admin.1')
.notification((notification) => {
console.log(notification.message); // no log
});
//Echo.channel('events').listen('NewUserRegister', (e) => console.log("RealTimeEventMessage: "+e.message));
</script>
enter image description here
I followed up some tutorials about echo and pusher. I configured all the project as necessary but object notifications not appear at browser. I uncoment the line

I have multiple Notifications dispatched at once but only one is sent and no error is logged

Notification::sendNow(Admin::all(),new NewMessageNotification($tic,$message,Admin::first()));
Notification::sendNow(Admin::all(),new TicketCreatedNotification($tic));
my first notification class
class NewMessageNotification extends Notification implements ShouldQueue
{
use Queueable;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(private Ticket $ticket,private TicketChat $chat,private $user)
{
//
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['database','broadcast'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->line('The introduction to the notification.')
->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 toArray($notifiable): array
{
return $this->chat->append(['from','to'])->toArray()+['ticket'=>$this->ticket->toArray()];
}
public function toBroadcast($notifiable): array
{
$count = ['un_read_side_bar_count'=>$this->user->myUnReadSideBar()->count()];
if($this->user instanceof Admin){
$count+=['unread_sellers_chat'=>$this->user->myUnreadChatsSellers()->count(),'unread_users_chat'=>$this->user->myUnreadChatsUsers()->count()];
}
return $this->chat->append(['from','to'])->toArray()+['ticket'=>$this->ticket->toArray()]+$count;
}
public function broadCastType(){
return 'broadcast.message.received';
}
}
my second notification class
class TicketCreatedNotification extends Notification implements ShouldQueue
{
use Queueable;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(public Ticket $ticket)
{
//
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['database','broadcast'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->line('The introduction to the notification.')
->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 toArray($notifiable)
{
return [
'ticketable'=>[
'name'=>$this->ticket->ticketable->name,
],
'subject'=>$this->ticket->subject,
'identifier'=>$this->ticket->identifier,
'un_read_user_messages_count'=>$this->ticket->un_read_user_messages_count,
'un_read_admin_messages_count'=>$this->ticket->un_read_admin_messages_count,
'created_at'=>Carbon::parse($this->ticket->created_at)->format('Y-m-d H:i:s'),
];
}
public function broadCastType(){
return 'broadcast.ticket.created';
}
}
enter image description here
from image of telescope above it shows pending but in jobs table and failed_jobs its not there, I have tried delaying the job but still to no avail I removed the implement ShouldQueue still no result is there anything I am missing

laravel notification does not work for me

I want to send an email to user with a message as below:
MessageController.php:
public function store(Request $request)
{
$user_id = auth()->user()->id;
$message = new Message;
$message->title = $request->title;
$message->body = $request->body;
$message->offer_id = $request->offer_id;
$message->user_id = $user_id;
$message->with_profile = $request->employeeProfile;
$message->save();
//return response()->json($message); -> this gives correct message
$offer = Offer::where('id', '=', $request->offer_id)->first();
//here I'm trying to get user Id, basing on offer (I knot I should use other way, but I'll correct it later
$user = User::where('id', '=', $offer->user_id)->first();
$user->notify(new OfferMessage($message)); -> this gives error "Undefined variable: message"
return response()->json(['created' => true], 201);
}
The problem is that it gives me an error: "Undefined variable: message", while I'm reciving correct message when I uncoment "return response()->json($message);"
What am I doing wrong here?
edit:
My Message.php class: (I don't have OfferMessage class)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use App\Notifications\OfferMessage;
class Message extends Model
{
use Notifiable;
}
edit2: Notifications/OfferMessage.php
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use App\Message;
class OfferMessage extends Notification
{
use Queueable;
public $message;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(Message $message)
{
$this->message = $message;
}
/**
* 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've got new message: '.$message->offer_id)
->line($message->title)
->line($message->body)
->line('Sent by:'.$message->user_id)
->line('Thank you for using our application!');
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
Change your OfferMessage Class toMail method
Change $message TO $this->message
public function toMail($notifiable)
{
return (new MailMessage)
->line("You've got new message: ".$this->message->offer_id)
->line($this->message->title)
->line($this->message->body)
->line('Sent by:'.$this->message->user_id)
->line('Thank you for using our application!');
}

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