Why notification event is not triggered in pusher? - laravel

When in Laravel 9 app logged user fill ContactUs form I need to send email to site support and show
notification in app for any logged support member. I make it with notification and pusher
In app/Notifications/ContactUsCreatedNotification.php :
<?php
namespace App\Notifications;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use App\Models\User;
class ContactUsCreatedNotification extends Notification
{
public $title;
public $content_message;
public $authorUser;
public function __construct(string $title, string $content_message, User $authorUser)
{
$this->title = $title;
$this->content_message = $content_message;
$this->authorUser = $authorUser;
}
public function via($notifiable)
{
return ['mail', 'broadcast']; // I added broadcast here
}
public function toMail($notifiable)
{
return (new MailMessage)->markdown('mail.ContactUsCreatedNotification', [
'title' => $this->title,
'content_message' => $this->content_message,
'authorUser' => $this->authorUser
]);
}
public function toArray($notifiable)
{
return [
'title' => $this->title,
'content_message' => $this->content_message,
'authorUser' => $this->authorUser,
];
}
}
I got email on configured mailtrap but Debug console of my pusher app has no event : https://prnt.sc/L9nXEfup_3i-
in .env :
BROADCAST_DRIVER=pusher
CACHE_DRIVER=file
FILESYSTEM_DISK=local
SESSION_DRIVER=database
SESSION_LIFETIME=120
PUSHER_APP_ID=NNNN
PUSHER_APP_KEY=XXXXX
PUSHER_APP_SECRET=XXXXX
PUSHER_APP_CLUSTER=eu
In resources/js/bootstrap.js :
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
// alert('resources/js/bootstrap.js')
console.log('process.env.MIX_PUSHER_APP_KEY::')
console.log(process.env.MIX_PUSHER_APP_KEY)
console.log('process.env.MIX_PUSHER_APP_CLUSTER::')
console.log(process.env.MIX_PUSHER_APP_CLUSTER)
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
forceTLS: true
});
In the app I have
"laravel/framework": "^v9.6.0",
"predis/predis": "^1.1",
"pusher/pusher-php-server": "^7.0",
and
"laravel-echo": "^1.11.7",
Any ideas why notification event is not triggered ?
UPDATED BLOCK # 1:
in .env file I set parameters
QUEUE_CONNECTION=redis
I do :
foreach ($supportManagers as $nextSupportManager) {
if ($nextSupportManager->user) {
$ret = Notification::sendNow($nextSupportManager->user, new ContactUsCreatedNotification(
$request->title,
$request->content_message,
auth()->user()
));
}
}
Also I tried to add Queueable definition i app/Notifications/ContactUsCreatedNotification.php file:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use App\Models\User;
class ContactUsCreatedNotification extends Notification implements ShouldQueue
{
use Queueable;
public $title;
public $content_message;
public $authorUser;
But I still get email in mailtrap and not events in pusher...
Thanks!

Related

Laravel Notification doesn't work when queued

I'm using notifications to send emails to the admin when a new note added by the user. If I don't use the ShouldQueue, all work fine.. When I use queue I got an error
ErrorException: Undefined property: App\Notifications\NewKidNote::$note
what might be the reason?
here is my notification code
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use App\Models\KidNote;
class NewKidNote extends Notification
{
use Queueable;
protected $note;
protected $kidname;
protected $userfullname;
protected $color;
protected $sentnote;
protected $kidid;
public function __construct($note)
{
$this->note = $note;
$this->kidname = $note->kid->name;
$this->userfullname = $note->user->fullname;
$this->color = $note->color;
$this->sentnote = $note->note;
$this->kidid = $note->kid_id;
}
public function via($notifiable)
{
return ['mail','database'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->subject('New Note added')
->greeting('Hello ')
->line('New Note has been added for '. $this->kidname. ' by '.$this->userfullname)
->line('Note Color: '.$this->color)
->line('Note')
->line($this->sentnote)
->action('You can also see the note here', route('admin.children.show',$this->kidid));
}
public function toDatabase($notifiable)
{
return [
'icon' => 'notepad',
'color' => $this->color,
'message' => 'New note added for '. $this->kidname ,
'link' => route('admin.children.show',$this->kidid)
];
}
}
Note to self.. Make sure you clean the cache and restart the queue :)) then it works fine!! This code runs perfectly. thanks

laravel 5.4 pusher(laravel echo) 403 error with private channel

sorry for my english it is not my main language.
i use laravel 5.4 + pusher + laravel echo for broadcasting.
No problem public channels everything works very well.
but on private channel i also get 403 error.
my event(newpsignal.php) :
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class newpSignal implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $user_id;
public function __construct($user_id)
{
$this->user_id=$user_id;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('reload-account-'.$this->user_id);
}
}
my channels.php
Broadcast::channel('reload-account-.{user_id}', function ($account,$user_id) {
return true; //Auth::id()===$user_id;
});
bootstrap.js
import Echo from 'laravel-echo'
window.Pusher = require('pusher-js');
window.Echo = new Echo({
authEndpoint: 'http://localhost/public/broadcasting/auth',
broadcaster: 'pusher',
key: '********', //its my key
cluster: 'eu',
encrypted: true,
});
other js code on blade(public listen work):
Echo.channel('<?php echo Redis::get('default_'.Auth::id());?>-market')
.listen('newSignal', function (e) {
doOrders(e.signal);
});
Echo.private('reload-account-<?php echo Auth::id();?>')
.listen('newpSignal', function (e) {
alert(e)
});
error:
Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException: in file C:\wamp64\www\vendor\laravel\framework\src\Illuminate\Broadcasting\Broadcasters\Broadcaster.php on line 65
Stack trace:
1. Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException->() C:\wamp64\www\vendor\laravel\framework\src\Illuminate\Broadcasting\Broadcasters\Broadcaster.php:65
2. Illuminate\Broadcasting\Broadcasters\Broadcaster->verifyUserCanAccessChannel() C:\wamp64\www\vendor\laravel\framework\src\Illuminate\Broadcasting\Broadcasters\PusherBroadcaster.php:50
3. Illuminate\Broadcasting\Broadcasters\PusherBroadcaster->auth() C:\wamp64\www\vendor\laravel\framework\src\Illuminate\Broadcasting\BroadcastManager.php:310
4. Illuminate\Broadcasting\BroadcastManager->__call() C:\wamp64\www\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php:221
5. Illuminate\Support\Facades\Facade->__callStatic() C:\wamp64\www\vendor\laravel\framework\src\Illuminate\Broadcasting\BroadcastController.php:19
6. Illuminate\Broadcasting\BroadcastController->authenticate() C:\wamp64\www\vendor\laravel\framework\src\Illuminate\Routing\Controller.php:54
7. call_user_func_array() C:\wamp64\www\vendor\laravel\framework\src\Illuminate\Routing\Controller.php:54
8. Illuminate\Routing\Controller->callAction() C:\wamp64\www\vendor\laravel\framework\src\Illuminate\Routing\ControllerDispatcher.php:45

Why mail laravel not working on the staging server?

I try on the my localhost, it works
But if I try on the staging server, it does not works
My controller like this :
<?php
use Illuminate\Support\Facades\Mail;
use App\Mail\OrderReceivedMail;
...
class PurchaseController
{
...
public function test() {
$order = $this->order_repository->find(416);
$user = $this->user_repository->find(1);
Mail::to($user)->send(new OrderReceivedMail($order, $order->store));
}
}
My mail like this :
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class OrderReceivedMail extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
public $order;
public $store;
public function __construct($order, $store)
{
$this->order = $order;
$this->store = $store;
$this->subject('subject');
}
public function build()
{
$mail_company = explode(',',config('app.mail_company'));
// dd($mail_company, $this->order->number, $this->store->name, 'test');
return $this->view('vendor.notifications.mail.email-order',['number'=>$this->order->number, 'store_name' => $this->store->name])->bcc($mail_company);
}
}
I try add this :
dd($mail_company, $this->order->number, $this->store->name, 'test');
on the mail
If in my localhost, the result of dd show
But if in the staging server, the result of dd not show
Seems if the staging server, it does not run this statement :
Mail::to($user)->send(new OrderReceivedMail($order, $order->store));
How can I solve this problem?
open config/mail.php, .env files and set your email driver as mail as bellow,
'driver' => env('MAIL_DRIVER', 'mail'), //you must set it in env file too
then you can send emails like bellow, note that emails.admin.member, is the path to your email template, in the example code, laravel will look for a blade template in the path, resources\views\emails\admin\member.blade.php
Mail::queue('emails.admin.member', $data, function($message) {
$message->subject("A new Member has been Registered" );
$message->from('noreply#mydomain.net', 'Your application title');
$message->to('yourcustomer#yourdomain.com');
});
or
Mail::send('emails.admin.member', $data, function($message) {
$message->subject("A new Member has been Registered" );
$message->from('noreply#mydomain.net', 'Your application title');
$message->to('yourcustomer#yourdomain.com');
});

Map Eloquent event to a dedicated class in Laravel does not work

I am trying to catch in Laravel 5.5 the eloquent.created event when a Post model is created, but for any reason it does not work. It looks like the event/listener mapping that is defined inside the EventServiceProvider.php does not work. My setup is as follows.
EventServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
protected $listen = [
'App\Events\PostWasPublished' => [
'App\Listeners\NotifyBlogSubscribers',
]
];
public function boot()
{
parent::boot();
//
}
}
NotifyBlogSubscribers.php listener
<?php
namespace App\Listeners;
use App\Events\PostWasPublished;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class NotifyBlogSubscribers
{
public function __construct()
{
//
}
public function handle(PostWasPublished $event)
{
dd('Inside NotifyBlogSubscribers');
}
}
PostWasPublished.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class PostWasPublished
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct()
{
dd('Inside PostWasPublished');
}
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
Post.php
<?php
namespace App\Models;
use App\Events\PostWasPublished;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
protected $events = [
'created' => PostWasPublished::class,
];
protected $fillable = ['user_id', 'title', 'body'];
public function comments() {
return $this->hasMany(Comment::class);
}
public function addComment($body) {
Comment::create([
'body' => $body,
'post_id' => $this->id
]);
}
public function user() {
return $this->belongsTo('App\User');
}
public function scopeFilter($query, $filters) {
if (array_key_exists('month', $filters)) {
$month = $filters['month'];
$query->whereMonth('created_at', Carbon::parse($month)->month);
}
if (array_key_exists('year', $filters)) {
$year = $filters['year'];
$query->whereYear('created_at', $year);
}
}
public static function archives() {
return static::selectRaw('year(created_at) as year, monthname(created_at) as month, count(*) published')
->groupBy('year', 'month')
->orderByRaw('min(created_at) desc')
->get()
->toArray();
}
public function tags() {
return $this->belongsToMany(Tag::class);
}
}
How do I test?
My first approach is to use tinker in the following way:
>>> App\Models\Post::create(['user_id' => '1', 'title' => 'some title', 'body' => 'lorem ipsum'])
=> App\Models\Post {#732
user_id: "1",
title: "some title",
body: "lorem ipsum",
updated_at: "2017-08-07 05:06:32",
created_at: "2017-08-07 05:06:32",
id: 62,
}
Also, when I create a post in the front-end it does not run into the dd() methods.
Also composer dump-autoload, php artisan clear-compiled or php artisan optimize did not do the trick. Any idea what I am doing wrong?
In Laravel 5.5 you will need to define a $dispatchesEvents property instead of a $events property. ($events was used in older Laravel versions).

Laravel Redis event broadcasting

I'm trying to use redis as a default broadcaster in laravel here is my .env fille
QUEUE_DRIVER=sync
APP_ENV=local
APP_DEBUG=true
APP_KEY=***********
DB_HOST=***************
DB_PORT=******************
DB_DATABASE=***************
DB_USERNAME=***********
DB_PASSWORD=*************
CACHE_DRIVER=file
SESSION_DRIVER=file
BROADCAST_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
I'm using this event class to broadcast
<?php
namespace App\Events;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;
use Log ;
class SomeEvent extends Event implements ShouldBroadcast
{
use SerializesModels;
public $data;
public function __construct($room, $data)
{
Log::debug($room);
Log::debug($data);
$this->data = array(
'room' => $room,
'data' => $data
);
}
public function broadcastOn()
{
Log::debug('in channel!!!');
return ['test-channel'];
}
}
when i fire the event inside a controller using
event(new SomeEvent("test room", "test message"));
I get the following error
[2016-02-29 19:17:38] local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'Pusher' not found' in C:\xampp\htdocs\TechInsights\vendor\laravel\framework\src\Illuminate\Broadcasting\BroadcastManager.php:132
Stack trace:
The most strange thing is when i change the method createPusherDriver inside the BroadcastManager.php
from
protected function createPusherDriver(array $config)
{
return new PusherBroadcaster(
new Pusher($config['key'], $config['secret'], $config['app_id'], Arr::get($config, 'options', []))
);
}
to
protected function createPusherDriver(array $config)
{
return new RedisBroadcaster(
$this->app->make('redis'), Arr::get($config, 'connection')
);
}
the event broadcasts in redis without any issue ! any ideas ? Why laravel using pusher even if i configured it to use redis ? what i'm missing ?
Have you tried clearing your config cache?
php artisan config:clear

Resources