PHP code example of amarwave / amarwave-laravel

1. Go to this page and download the library: Download amarwave/amarwave-laravel library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

amarwave / amarwave-laravel example snippets


use AmarWave\Laravel\AmarWave;

AmarWave::trigger('orders', 'placed', ['order_id' => 42]);

AmarWave::triggerBatch([
    ['channel' => 'chat-1', 'event' => 'message', 'data' => ['text' => 'Hello']],
    ['channel' => 'chat-2', 'event' => 'message', 'data' => ['text' => 'World']],
]);

\AmarWave::trigger('orders', 'placed', ['order_id' => 42]);

use AmarWave\AmarWave;

class OrderController extends Controller
{
    public function __construct(private readonly AmarWave $aw) {}

    public function store(Request $request): JsonResponse
    {
        $order = Order::create($request->validated());
        $this->aw->trigger('orders', 'placed', $order->toArray());
        return response()->json($order, 201);
    }
}

'connections' => [
    'amarwave' => [
        'driver' => 'amarwave',
    ],
],

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class OrderPlaced implements ShouldBroadcast
{
    public function __construct(public readonly array $order) {}

    public function broadcastOn(): array
    {
        return [
            new Channel('orders'),
            new PrivateChannel("user.{$this->order['user_id']}"),
        ];
    }

    public function broadcastAs(): string { return 'order.placed'; }

    public function broadcastWith(): array
    {
        return ['order_id' => $this->order['id'], 'total' => $this->order['total']];
    }
}

broadcast(new OrderPlaced($order));

use Illuminate\Support\Facades\Broadcast;

Broadcast::channel('user.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

Broadcast::channel('presence-room.{roomId}', function ($user, $roomId) {
    $room = \App\Models\Room::find($roomId);
    if ($room?->members()->where('user_id', $user->id)->exists()) {
        return ['id' => $user->id, 'name' => $user->name];
    }
    return false;
});
bash
php artisan vendor:publish --tag=amarwave-config