I'm trying to do some real-time push notifications using Laravel WebSockets as a socket server and Laravel Echo with Events.
When I'm doing it on Channel, it is working fine, but now I want it to send it to private channel.
Channel('reservation.' . $this->random_key);
to
PrivateChannel('reservation.' . $this->random_key);
NewReservationEvent.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class NewReservationEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
public $random_key;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($message, $user)
{
$this->message = $message;
$this->random_key = $user->random_key;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('reservation.' . $this->random_key);
}
public function broadcastAs()
{
return 'reservation.event';
}
}
routes/channels.php
<?php
use Illuminate\Support\Facades\Broadcast;
/*
|--------------------------------------------------------------------------
| Broadcast Channels
|--------------------------------------------------------------------------
|
| Here you may register all of the event broadcasting channels that your
| application supports. The given channel authorization callbacks are
| used to check if an authenticated user can listen to the channel.
|
*/
Broadcast::channel('App.Models.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
Broadcast::channel('reservation.{random_key}', function ($user, $random_key){
return true;
});
routes/web.php
Route::get('/sendEvent', function () {
$superAdmins = User::where('role', 'Super')->get();
foreach ($superAdmins as $superAdmin) {
$message = 'Reservation added by';
event(new NewReservationEvent($message, $superAdmin));
}
});
BroadcastServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes(['middleware' => ['auth', 'checkRole:Super,Admin,Customer']]);
require base_path('routes/channels.php');
}
}
And here is the Echo on my view:
Echo.private('reservation.{{ auth()->user()->random_key }}')
.listen('.reservation.event', (e) => {
console.log(e.message);
$("#refreshThisDropdown").load(window.location.href + " #refreshThisDropdown");
$("#refreshThisDropdown").load(" #refreshThisDropdown > *");
toastr.success(e.message, "Hello there");
})
It all works fine on Channel mode, I want to make it private just for more security.