PHP code example of swarakaka / bridge-laravel

1. Go to this page and download the library: Download swarakaka/bridge-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/ */

    

swarakaka / bridge-laravel example snippets


use Bridge\Bridge;

class CustomerController extends Controller
{
    public function index(Request $request)
    {
        return Bridge::render('Customers/Index', [
            'customers' => CustomerResource::collection(Customer::paginate(20)),
            'filters'   => ['search' => $request->string('search')->toString()],
            'stats'     => Bridge::defer(fn () => Customer::stats()),   // loaded after first render
            'filtersUi' => Bridge::lazy(fn () => Filter::all()),        // only on partial reload
        ]);
    }

    public function store(StoreCustomerRequest $request)
    {
        $customer = Customer::create($request->validated());

        return Bridge::redirect()
            ->route('customers.show', $customer)
            ->with('customer', CustomerResource::make($customer))
            ->flash('Customer created.')
            ->created();
    }
}

// bootstrap/app.php
$middleware->replaceInGroup('web', PreventRequestForgery::class, \Bridge\Http\Middleware\VerifyCsrfToken::class);

// routes/web.php — one stream per user, subscribed to a shared and a private channel
Route::get('/events', fn () => Bridge::stream()->channels(fn ($user) => ['customers', "user.{$user->id}"]))
    ->middleware('auth:sanctum');

// Anywhere: controllers, jobs, listeners
Bridge::to('customers')->invalidate(['customers']);            // clients partial-reload these props
Bridge::to("user.{$id}")->notify('Saved', 'success');           // toast
Bridge::to("user.{$id}")->prop('unreadCount', 3);               // push a small prop
Bridge::to('customers')->event('customer.created', $resource);  // application event

// Or mark an event class, mirroring ShouldBroadcast
class CustomerCreated implements ShouldStream {
    public function streamOn(): array { return ['customers']; }
    public function toStream(): array { return [StreamMessage::event('customer.created', [...]), StreamMessage::invalidate(['customers'])]; }
}

// One-off producer streams
Route::post('/export', fn () => Bridge::stream(function (StreamWriter $s) {
    $s->progress('export', 0.5, 'Halfway');
    $s->emit('export.done', ['rows' => 10]);
}));

// Client-requested channels are authorized like broadcast channels
Bridge::channel('tenant.{id}', fn (User $user, string $id) => $user->tenant_id === (int) $id);
bash
composer bridge:install        # publishes config/bridge.php and resources/views/app.blade.php