• Start

Languages

/

PHP

/

v2 (alpha)

/

Concepts

Live queries

Subscribe to real-time changes from SurrealDB over a WebSocket connection with version 2 of the PHP SDK.

Live queries notify your application whenever records that match a query are created, updated, or deleted. You start a LIVE SELECT statement to get a query ID, then iterate the messages the server pushes for that ID.

Run a LIVE SELECT statement with run(). The result is the live query ID.

[$queryId] = $db->run('LIVE SELECT * FROM person');

Pass the ID to live(). It returns an iterable of LiveMessage objects, one per change. Each message carries the action, the affected record ID, and the new value.

use SurrealDB\SDK\Live\LiveAction;

foreach ($db->live($queryId) as $message) {
match ($message->action) {
LiveAction::Create => handleCreate($message->value),
LiveAction::Update => handleUpdate($message->value),
LiveAction::Delete => handleDelete($message->record),
LiveAction::Killed => break,
};
}

A foreach over live() blocks the current PHP process while it waits for the next message. The standard PHP runtime (PHP-FPM or the CLI) handles one task per worker, so a process parked on a live query cannot serve anything else.

To run live queries alongside the rest of your application, choose an asynchronous runtime or run dedicated workers. See Runtimes and workers for configuring PHP-FPM with dedicated workers, OpenSwoole, and FrankenPHP.

Every message has an action from the LiveAction enum:

ActionDescription
LiveAction::CreateA new record matched the query
LiveAction::UpdateA matching record was modified
LiveAction::DeleteA matching record was removed
LiveAction::KilledThe live query was stopped on the server

Stop a live query by running a KILL statement with its ID. The loop receives a final LiveAction::Killed message and ends.

$db->run('KILL $id', ['id' => $queryId]);

Was this page helpful?