I have done every installation related to Laravel Websocket. Here's what I'm trying to do: I have a table in the database where I keep my orders. When a new order arrives, I want to print it to the console on my home page blade.
I would be glad if you help. Thanks.
CodePudding user response:
You can use model event like below, in your Order model
protected static function booted()
{
//everytime when new order is created this function will be called
static::created(function ($order) {
//then broadcast event
NewOrder::dispatch($order);
});
}
Then you have to define channel in youre route/channel.php
use App\Models\Order;
Broadcast::channel('newOrder', function ($user) {
return $user->id;
});
Then create event php artisan make:event NewOrder
class NewOrder implements ShouldBroadcast
{
/**
* The user that created the server.
*
* @var \App\Models\User
*/
public $user;
/**
* Create a new event instance.
*
* @param \App\Models\User $user
* @return void
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('newOrder');
}
}
then listen for NewOrder event in newOrder Channel
Echo.channel(`newOrder`)
.listen('NewOrder', (e) => {
console.log(e.order);
});
Read Documentation more info https://laravel.com/docs/9.x/broadcasting#pusher-channels