Laravel notification with one notification class - php

In my web app I have added the notification functionalities.
There are 3 notification class.
App/Notifications/
NotifWhenLiked.php
NotifyWhenStoryCommented.php
NotifyWhenAuthorFollowed.php
I want to make these task with one single Notification class. Is there any easiest way to solve this ?
Here is the code of one class
<?php
namespace App\Notifications;
use App\Http\Resources\Users;
use App\Model\User;
use App\Model\Story;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class NotifyWhenLiked extends Notification implements ShouldQueue
{
use Queueable;
public $user;
public $story;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(Story $story, User $user)
{
$this->user = $user;
$this->story = $story;
}
/**
* 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 toDatabase($notifiable)
{
return [
'notification' => "<strong>".$this->user->name."</strong>". ' liked your story '. "<strong>".$this->story->title."</strong>",
'Storylink' => '/story/'.$this->story->url_key,
'Userlink' => '/a/'.$this->user->profile->username
];
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
'notification' => $this->user->name. ' liked your story '. "<strong>".$this->story->title."</strong>",
'username' => $this->user->profile->username,
];
}
}

You might try to store the different notification types into an array e.g. a config file.
return [
'when_liked' => [
'notification_text' => '%s liked your story %s',
'story_link' => '/story/%s'
],
'when_commented' => [
'notification_text' => '%s commented on your story %s',
'story_link' => '/story/%s'
]
]
You can make a general Notification Class, which takes care about handling the notification stuff.
$whenLikedNotification = new YourCustomNotificationClass('when_liked');
$whenLikedNotification->trigger();
In the Constructor you can handle the config stuff.

I think you can use a event to do it
Create a event and call all listener(WhenLiked, WhenStoryCommented, WhenAuthorFollowed) that is related with event

Related

Laravel 8: Undefined property: App\Notifications\ResetPassword::$queue

I want tp apply queue for my Notifications, so I implemented that at my Notification which ResetPassword:
class ResetPassword extends Notification implements ShouldQueue
Then I ran php artisan queue:table and migrate it so the table jobs created successfully at the DB.
And also change the QUEUE_CONNECTION to database at .env file and re-run php artisan serve.
But when I test this and clicked on reset password link, a new table row must be added to jobs table but it does not.
And instead of that, this error returns:
ErrorException Undefined property:
App\Notifications\ResetPassword::$queue
...\notification\vendor\laravel\framework\src\Illuminate\Notifications\NotificationSender.php:195
So what is going wrong here ? How can I fix this issue ?
I would really appreciate any idea or suggestion from you guys...
Thanks in advance.
UPDATE #1:
ResetPassword.php:
<?php
namespace App\Notifications;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Lang;
class ResetPassword extends Notification implements ShouldQueue
{
/**
* The password reset token.
*
* #var string
*/
public $token;
/**
* 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);
}
return (new MailMessage)
->subject('subject goes here')
->line('This email is sent to you')
->action(Lang::get('Reset Password'), url(config('app.url').route('password.reset', ['token' => $this->token, 'email' => $notifiable->getEmailForPasswordReset()], false)))
->line(Lang::get('Until the next 60 minutes you can use this link', ['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 building the notification mail message.
*
* #param \Closure $callback
* #return void
*/
public static function toMailUsing($callback)
{
static::$toMailCallback = $callback;
}
}
Look Like you have forgot to use Queueable Trait in your notification
use Illuminate\Bus\Queueable;
class ResetPassword extends Notification implements ShouldQueue
{
use Queueable;
Queueable trait has propety $queue
Ref:https://laravel.com/docs/8.x/notifications#queued-notifications-and-database-transactions

My custom Mail Notification isn't sending while all the other are

I have a weird issue in my website. I have several Notifications such as Email Verification and Password Reset that are sending properly. However, I made my own notification that sends an url with a UUID to the user and unfortunately, it doesn't send.
I tried every way: 'Notification::route', notify the user directly, nothing works. Actually, notifying the user directly would be bad since I need to send it to an email address not attached to any model.
Anyway, here's the code for the notification. Keep in mind the other notifications work, so I doubt it is the issue.
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class NewEmail extends Notification
{
use Queueable;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($uuid)
{
$this->uuid = $uuid;
}
/**
* 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(__('messages.newEmailAsked'))
->action(__('messages.newEmailConfirm'), config('app.frontend_url') . '/verify-new-email?code=' . $this->uuid)
->line(__('messages.newEmailIgnore'));
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
public function addNewEmail($email) {
if(User::where('email', $email)->count() === 0) {
$uuid = Str::uuid();
NewEmail::create(['email' => $email, 'unique_code' => $uuid, 'user_id' => $this->id]);
Notification::route('mail', $email)->notify(new \App\Notifications\NewEmail($uuid));
} else {
return 'Email already exists.';
}
}
I really don't get why this notification isn't sent while the other are...
Weirdly enough, the problem fixed itself when I did the actual path the user would take instead of using Tinker.
Just had to $user->addNewEmail($newEmailHere) and it worked properly...
You have not defined the $uuid variable in your Queueable class

email notification in laravel 5.5 i get this error ```Trying to access array offset on value of type null```

i want to get email notification each time a new user is registered but after creating php artisan make:notification Taskcompleted and added Notification::route('mail','admin#gmail.com')->notify(new TaskCompleted()); like this in my contoller
public function store(Request $request){
$employee = request()->validate([
'employee_id' => 'required|max:250',
'name' => 'required|max:100',
'place_of_birth' => 'nullable|max:100',]);
Notification::route('mail','admin#gmail.com')->notify(new TaskCompleted());
i keep getting this error
Trying to access array offset on value of type null i have imported the necessary class and configured my .env file with mailtrap,still yet same error
taskcompleted file
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class TaskCompleted 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', 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 [
//
];
}
}
ok, I got the solution I was using PHP 7.4 for laravel 5.5 so I downgraded it to PHP 7.2 works fine now

Laravel custom user verification email issue

In my laravel application i'm trying to create a customized user verification email template.
First I created a folder called, Notifications inside the App, Inside my Notifications folder I have a file called CustomVerifyEmailNotification.php
app/Notifications/CustomVerifyEmailNotification.php
Following is my code inside the CustomVerifyEmailNotification.php
<?php
namespace Illuminate\Auth\Notifications;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\URL;
class CustomVerifyEmailNotification extends Notification
{
/**
* The callback that should be used to build the mail message.
*
* #var \Closure|null
*/
public static $toMailCallback;
/**
* 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)
{
$verificationUrl = $this->verificationUrl($notifiable);
if (static::$toMailCallback) {
return call_user_func(static::$toMailCallback, $notifiable, $verificationUrl);
}
return (new MailMessage)
->subject(Lang::get(''.('sentence.Verify Email Address').''))
->line(Lang::get(''.('sentence.If you did not create an account, no further action is required.').''));
}
/**
* Get the verification URL for the given notifiable.
*
* #param mixed $notifiable
* #return string
*/
protected function verificationUrl($notifiable)
{
return URL::temporarySignedRoute(
'verification.verify',
Carbon::now()->addMinutes(Config::get('auth.verification.expire', 60)),
[
'id' => $notifiable->getKey(),
'hash' => sha1($notifiable->getEmailForVerification()),
]
);
}
/**
* 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;
}
}
Then I changed my User.php according to following code
<?php
namespace App;
use App/Notifications/CustomVerifyEmailNotification;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Cashier\Billable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable,Billable;
use HasRoles;
public function sendEmailVerificationNotification()
{
$this->notify(new CustomVerifyEmailNotification);
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name','last_name', 'email', 'password','username','mobile','propic','user_roles','user_source',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
But,
use App/Notifications/CustomVerifyEmailNotification;
showing me an error saying syntax error, unexpected '/', expecing ';' or ','
Because of that I'm also getting an error here
public function sendEmailVerificationNotification()
{
$this->notify(new CustomVerifyEmailNotification);
}
error is, undefined type 'App\CustomVerifyEmailNotification'
How can I fix this issue and create this custom verification email
I'm using laravel 6
The namespace should be
namespace App\Notifications
and not
namespace Illuminate\Auth\Notifications;
And in the user.php instead of
use App/Notifications/CustomVerifyEmailNotification;
you should use
use App\Notifications\CustomVerifyEmailNotification;

laravel 5.3 database notification customization

I am creating laravel 5.3 database notifications.I have created notifications as per video published on https://laracasts.com/series/whats-new-in-laravel-5-3/episodes/10 ,
Now i want to add custom fields to the notification table as per my requirements.
Please help me how to pass custom data to notification and access it.
When I needed to put custom fields to Notification, I'd just put on data field, as it is a Json field, works perfectly. Like this:
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
class TaskNotification extends Notification
{
use Queueable;
private $message;
/**
* #param String $message
*/
public function __construct($message=false)
{
if ($message)
$this->message = $message;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['database'];
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
'message' => $this->message,
'link' => route('mymodel.show'),
'task'=> 1, // This is one variable which I've created
'done'=> 0 // This is one variable which I've created
];
}
}

Categories