Render a view as response of Event Broadcasting - laravel

Hi there i'm under development of a Laravel webapp that use events broacasting troug redis, and socket.io. All is working fine, but i tring to return a rendered view as response of Event.
Mi event is something like this:
<?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 EventName implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* #return void
*/
public $data;
public function __construct()
{
$this->data = array(
'power'=> 'Funziona',
'view'=> view('dashboard.partials.messages')->render()
);
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return ['test-channel'];
}
}
and i use this code to render response on the page:
<script src="/frontend/socket.io.js"></script>
<script>
var socket = io('http://1clickfashion.com:3002');
socket.on("test-channel:App\\Events\\EventName", function(message){
// increase the power everytime we load test route
alert(message.data.power);
$('#messages').html('');
$('#messages').html(message.data.view);
});
</script>
The "power" alert is displayed correctly but the view don't work as well. In another view i'm use the view as return response()->json($view) and works perfectly... Someone have similar issues?

For anyone that struggle in this issue, solved by passing the view as variable rendered in Controller. Like this.
In Controller:
$view = view('dashboard.partials.messages')->with('post', $post_c)->render();
event(new \App\Events\Post($view));
in event:
public $data;
public function __construct($view)
{
$this->data = array(
'view'=> $view
);
}

Related

How to solve Laravel Pusher Error data content of this event exceeds

I did the update to Laravel 9 today. Before, Pusher worked well on the application.
Now, I receive always the following error:
Pusher error: The data content of this event exceeds the allowed maximum (10240 bytes)
I didn't change the content.
I tested to change the content with the given supplier_id, with a fake id like "ee" and without any restrictions.
In the console log, I have the following result:
Why does pusher work, even there is an error in the backend?
<?php
namespace App\Events\Kanban;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class KanbanOrderCreatedEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $kanbanOrder;
public function __construct($kanbanOrder)
{
$this->kanbanOrder = $kanbanOrder;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return ['kanbanOrders.'.$this->kanbanOrder->network_supplier_id];
}
public function broadcastAs()
{
return 'kanbanOrderCreated';
}
public function broadcastWith()
{
return ['supplier_id' => $this->kanbanOrder->network_supplier_id];
}
}

Unable to broadcast Notification in Laravel

I am trying to use Pusher Notificaiton system to use web sockets to update the current page with the message "YOu have a new Notification" and the bell icon indicating the number of unread notifications. I registered the Events and Listeners and have implemented ShouldBroadcase and connected everything. But I am not getting any message. And unless the page reloads, I am not getting the no. of unread notifications as well.
Here are my codes
Event
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class NewNotificationEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
protected $data;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct($data)
{
$data = $this->data;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return ['my-channel'];
}
public function broadcastAs()
{
return 'my-event';
}
}
Listener
<?php
namespace App\Listeners;
use App\Events\NewNotificationEvent;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use DB;
use Illuminate\Support\Facades\Auth;
class NewNotificationListener
{
/**
* Create the event listener.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* #param NewNotificationEvent $event
* #return void
*/
public function handle(NewNotificationEvent $event)
{
$users = Auth::user();
DB::select('CALL notification_tbl(?)',array($users->id));
}
}
Controller
if(Gate::allows('manage-users')){
$userid = $request->userid;
$notf = $request->notf;
$priority = $request->priority;
DB::table('notifications')->insert(['user_id'=>$userid,'notf_message'=>$notf,'priority'=>$priority]);
$data = array(
'userid'=>$userid,
'priority'=>$priority,
'notf_message'=>$notf,
);
event (new NewNotificationEvent($data));
// DB::select('CALL notification_tbl(?)',array($userid));
return response()->json([
'success'=>true,
'msg'=>"User Notified",
]);
}
abort(403, "This Page is only available for Admin");
}
}
Notification sent from Backend (Backend Controller)
public function sendNotf(Request $request){
if(Gate::allows('manage-users')){
$userid = $request->userid;
$notf = $request->notf;
$priority = $request->priority;
DB::table('notifications')->insert(['user_id'=>$userid,'notf_message'=>$notf,'priority'=>$priority]);
DB::select('CALL notification_tbl(?)',array($userid));
$data = array(
'userid'=>$userid,
'priority'=>$priority,
'notf_message'=>$notf,
);
// event (new NewNotificationEvent($data));
return response()->json([
'success'=>true,
'msg'=>"User Notified",
]);
}
abort(403, "This Page is only available for Admin");
}
JS Code (Available in the common blade page- the one which includes the Navbar and is included in every other page)
<script src="https://js.pusher.com/7.0/pusher.min.js"></script>
<script>
// Enable pusher logging - don't include this in production
Pusher.logToConsole = true;
var pusher = new Pusher('be850f6784915a1d43b8', {
cluster: 'ap2'
});
var channel = pusher.subscribe('user-channel');
channel.bind('user-channel', function(data) {
alert(JSON.stringify(data));
});
</script>
First of all, make your notification by php artisan make:notification exNotification
then implement your notification in toBroadcast function
return (new BroadcastMessage([
//
]))
Finally use
$user->notify(new exNotification());
Also, you can define your channel name in receivesBroadcastNotificationsOn in User Model
public function receivesBroadcastNotificationsOn()
{
return 'user.'.$this->id;
}
for more detail please visit :
Notifications
composer require pusher/pusher-php-server
PUSHER_APP_ID=322700
BROADCAST_DRIVER=pusher
// Get the credentials from your pusher dashboard
PUSHER_APP_ID=XXXXX
PUSHER_APP_KEY=XXXXXXX
PUSHER_APP_SECRET=XXXXXXX
//header or footer file
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="//js.pusher.com/3.1/pusher.min.js"></script>
<script type="text/javascript">
var pusher = new Pusher('API_KEY_HERE', {
encrypted: true
});
// Subscribe to the channel we specified in our Laravel Event
var channel = pusher.subscribe('my-channel');
channel.bind('App\\Events\\NewNotificationEvent', function(data) {
console.log('New event');
//reload page for append data to any div
});
</script>

Laravel 7 queued email very slow with attachment but fast without

I use Laravel 7 queues / jobs to send a newsletter to multiple addresses and it works well and rather fast. But when I send a single email with attachment (22ko PDF), it takes nearly 3 - 5 minutes to get through. Any clues? I use database driver and Mailgun API.
How can I see if the slow process time is from Laravel app or Mailgun or else?
I tried to use SendEmailJob::dispatchNow($data); but it does not speed up the process.
app\Http\controllers/EmailController.php
App\EmailController
use App\Job\SendEmailJob;
public function send()
{
$data = array(
'from_name'=>from_name',
'from_email'=>'admin#domain.com',
'to_name'=>$user->firstname." ".$user->name,
'to_email'=>$user->email,
'subject'=>'This is test email',
'reply_to'=>noreply#domain.com,
'model'=>$invoice,
'locale'=>app()->getLocale(),
'user'=>$user,
'view'=>'emails.invoice',
'filefullpath'=>$fullfilepath,
);
SendEmailJob::dispatch($data);
}
App\Jobs\SendEmailJob.php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Mail\SendView;
use Mail;
class SendEmailJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $data;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
$email = new SendView($this->data);
$email->replyTo($this->data['reply_to']);
$email->subject($this->data['subject']);
if(isset($this->data['filefullpath']))
{
$email->attach($this->data['filefullpath']);
}
Mail::to($this->data['to_email'], $this->data['to_name'])->send($email);
}
}
App\Mail\SendView.php
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class SendView extends Mailable
{
use Queueable, SerializesModels;
protected $data;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$view = $this->data['view'];
$user = $this->data['user'];
$model = $this->data['model'];
$locale = $this->data['locale'];
$array = $this->data['array'];
return $this->view($view, compact('user', 'model','locale','array'));
}
}
Please help! Thanks.

Keep PHPMailler connection alive over Laravel's queue

I want to send many emails.
Currently I write basic code use PHPMailler to send mail using queue. It works, but everytime new queue is run, it have to connect to SMTP again, so i get bad perfomance.
I find SMTPKeepAlive property on PHPMailler documentation:
$phpMailer = New PHPMailer();
$phpMailer->SMTPKeepAlive = true;
Is it imposible and how to keep $phpMailler object for next queue? So PHPMailler have not to connect again by using previous connection.
If you are using Laravel then you have to use Laravel's feature inbuilt.
Please find below documents:
https://laravel.com/docs/5.6/mail
Please find a piece of code for send mail and adding in a queue:
use App\Mail\EmailVerifyMail;
\Mail::queue(new EmailVerifyMail($users));
EmailVerifyMail.php
<?php
namespace App\Mail;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class EmailVerifyMail extends Mailable
{
use Queueable, SerializesModels;
public $user;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$this->to($this->user)->subject(__('mail.subjects.verification_link', ['USERNAME' => $this->user->name]));
return $this->view('mails/emailVerify', ['user' => $this->user]);
}
}

Laravel 5.2 not broadcasting events

I've tried to broadcast event with pusher. But after a long hours of debugging I am still without a working solution.
Pusher works great, it's getting events from the debug console. Laravel is also firing the event. I also set up the queue and broadcasting configuration, but I noticed that my queue listener never getting any response.
This is my event listener:
<?php
namespace App\Listeners;
use App\Events\SomeEvent;
use Illuminate\Contracts\Queue\ShouldQueue;
class EventListener implements ShouldQueue
{
/**
* Create the event listener.
*
* #return void
*/
public function __construct()
{
}
/**
* Handle the event.
*
* #param SomeEvent $event
* #return void
*/
public function handle(SomeEvent $event)
{
//dd($event);
}
}
Routes:
Route::get('event', function () {
event(new App\Events\SomeEvent());
return "event fired";
});
Event file:
<?php
namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class SomeEvent extends Event implements ShouldBroadcast
{
use SerializesModels;
public $data;
public $x = 1111;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct()
{
$this->data = array(
'power'=> '10'
);
}
/**
* Get the channels the event should be broadcast on.
*
* #return array
*/
public function broadcastOn()
{
return ['test_channel'];
}
}
Edit:
i reinstalled laravel and now the queue seems to respond and create row in the job table. but the pusher still dont recive any events from laravel.
Your App\Providers\EventServiceProvider needs to be made aware of the events and listeners.
protected $listen = [
App\Events\SomeEvent::class => [
App\Listeners\SomeListener::class,
],
];
These can be automatically populated by running php artisan event:generate.

Resources