wargasipil / connectrpc-laravel
Connect RPC and gRPC-Web for Laravel: serve protobuf services from your routes, call them with typed clients, and generate both with a protoc plugin written in PHP.
Requires
- php: ^8.2
- google/protobuf: ^4.30 || ^5.0
- guzzlehttp/guzzle: ^7.8 || ^8.0
- illuminate/contracts: ^11.0 || ^12.0 || ^13.0
- illuminate/http: ^11.0 || ^12.0 || ^13.0
- illuminate/routing: ^11.0 || ^12.0 || ^13.0
- illuminate/support: ^11.0 || ^12.0 || ^13.0
Requires (Dev)
- orchestra/testbench: ^9.0 || ^10.0 || ^11.0
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^10.5 || ^11.5 || ^12.0 || ^13.0
Suggests
- ext-protobuf: Faster protobuf encoding and decoding. The package works without it.
- ext-zlib: Needed for gzip compression of requests and responses. Without it, calls are sent and answered uncompressed.
Provides
None
Conflicts
None
Replaces
None
README
Serve Connect and gRPC-Web services from Laravel
routes, and call Connect services with typed clients. Both are generated
from your .proto files by protoc-gen-connect-laravel, a protoc plugin
written in PHP that ships with the package.
// routes/api.php use App\Rpc\GreetHandler; use Wargasipil\ConnectRpc\Laravel\Facades\Connect; Connect::service(GreetHandler::class)->middleware('auth:sanctum'); // POST /api/greet.v1.GreetService/Greet (and GET, for NO_SIDE_EFFECTS methods)
// app/Rpc/GreetHandler.php final class GreetHandler implements GreetServiceInterface { public function greet(GreetRequest $request, Context $ctx): GreetResponse { return new GreetResponse(['greeting' => "Hello, {$ctx->user()->name}!"]); } }
Any Connect or gRPC-Web client calls it: connect-web and grpc-web in the
browser, connect-go, and the generated PHP client. The handler gets typed
messages and a Context; routes, middleware, auth, rate limits and
route:cache work as for any Laravel route. It is pure PHP: no extensions
beyond what Laravel needs, no worker processes, so it runs on shared hosting.
- What you get
- Install
- Quick start
- Routing
- The Context
- Errors
- Server streaming
- gRPC-Web and browsers
- CORS
- Typed clients
- Configuration
- Shared hosting
- Testing your services
- Example app
- What it does not do
- Compatibility
- How it works
- Design decisions
- Development
What you get
| Protocols (server) | Connect, gRPC-Web (application/grpc-web, +proto, +json, grpc-web-text) |
| Unary methods | Yes, with POST; also GET for methods marked NO_SIDE_EFFECTS |
| Server-streaming methods | Yes, each message sent as soon as it is yielded |
| Client-streaming and bidirectional methods | No: they answer unimplemented (PHP gets the whole request body at once) |
| Plain gRPC (HTTP/2 trailers) | No: use gRPC-Web or Connect |
| Formats | Protobuf binary and JSON (Protobuf's JSON mapping, unknown fields ignored) |
| Compression | gzip, both ways (needs ext-zlib, which almost every PHP has) |
| Timeouts | Connect-Timeout-Ms and grpc-timeout become a deadline in the Context |
| Errors | ConnectException with all 16 codes and error details; Laravel's exceptions mapped for you, also those thrown by middleware |
| Routing | Normal Laravel routes: prefixes, groups, middleware, names, route:cache, route:list |
| Typed client | Connect protocol on Laravel's HTTP client: unary and server streams, JSON or binary, gzip, timeouts; Http::fake() works |
| Code generation | protoc-gen-connect-laravel (PHP, a Composer bin), next to Google's PHP message generator |
| Tested with | Connect's conformance suite v1.0.7 (server: 518 of 518 cases; client: 315 of 323, the other 8 being two cancellation cases PHP cannot do) and connect-go 1.19 clients and servers |
| Runtime dependencies | google/protobuf (pure PHP; ext-protobuf used when present), guzzlehttp/guzzle, illuminate/* |
Install
composer require wargasipil/connectrpc-laravel
The service provider and the Connect facade are discovered automatically.
You also need buf (or protoc) on
your development machine to generate code. Code generation happens only
there: the generated files are committed, and the server never runs
protoc.
Add a buf.gen.yaml to your app. It runs Google's PHP generator for the
message classes and this package's plugin for the services, into the same
folder:
version: v2 inputs: - directory: proto plugins: # Message classes. protoc_builtin needs protoc on PATH; or use the # remote plugin: `- remote: buf.build/protocolbuffers/php` - protoc_builtin: php out: generated # <Service>Interface, <Service>Descriptor and <Service>Client. - local: [php, vendor/bin/protoc-gen-connect-laravel] out: generated
Then autoload the generated folder in composer.json (the namespaces
follow your proto packages; for package greet.v1; they are Greet\V1\
and GPBMetadata\Greet\V1\):
"autoload": { "psr-4": { "App\\": "app/", "Greet\\": "generated/Greet/", "GPBMetadata\\Greet\\": "generated/GPBMetadata/Greet/" } }
buf generate && composer dump-autoload
The plugin follows Google's PHP naming rules exactly (php_namespace,
php_metadata_namespace, php_class_prefix, reserved words such as
PBClass), so its files sit next to the message classes. On Windows, give
buf the PHP path if php is not on PATH:
local: [C:/path/to/php.exe, vendor/bin/protoc-gen-connect-laravel].
Quick start
1. Define the service
// proto/greet/v1/greet.proto syntax = "proto3"; package greet.v1; service GreetService { rpc Greet(GreetRequest) returns (GreetResponse) { option idempotency_level = NO_SIDE_EFFECTS; // also allow GET } rpc GreetMany(GreetManyRequest) returns (stream GreetResponse); } message GreetRequest { string name = 1; } message GreetResponse { string greeting = 1; } message GreetManyRequest { string name = 1; int32 count = 2; }
buf generate writes the message classes and, for the service:
Greet\V1\GreetServiceInterface: what your handler implements.Greet\V1\GreetServiceDescriptor: the service name and its methods, used for routing (no reflection at request time).Greet\V1\GreetServiceClient: a typed client.
2. Implement it
namespace App\Rpc; use Greet\V1\GreetManyRequest; use Greet\V1\GreetRequest; use Greet\V1\GreetResponse; use Greet\V1\GreetServiceInterface; use Wargasipil\ConnectRpc\Code; use Wargasipil\ConnectRpc\ConnectException; use Wargasipil\ConnectRpc\Context; final class GreetHandler implements GreetServiceInterface { // Built by Laravel's container: ask for any service you need. public function __construct(private readonly GreetingRepository $greetings) { } public function greet(GreetRequest $request, Context $ctx): GreetResponse { if ($request->getName() === '') { throw new ConnectException(Code::InvalidArgument, 'name is required'); } return new GreetResponse(['greeting' => $this->greetings->for($request->getName())]); } public function greetMany(GreetManyRequest $request, Context $ctx): iterable { for ($i = 1; $i <= $request->getCount(); $i++) { yield new GreetResponse(['greeting' => "Hello #{$i}, {$request->getName()}!"]); } } }
3. Route it
// routes/api.php Connect::service(GreetHandler::class);
That's all. Try it:
curl -X POST http://localhost:8000/api/greet.v1.GreetService/Greet \ -H 'Content-Type: application/json' -d '{"name":"Ana"}' # {"greeting":"Hello, Ana!"} curl 'http://localhost:8000/api/greet.v1.GreetService/Greet?connect=v1&encoding=json&message=%7B%22name%22%3A%22Ana%22%7D' # {"greeting":"Hello, Ana!"}
4. Call it from PHP (optional)
$client = new GreetServiceClient('https://api.example.com/api'); $reply = $client->greet(new GreetRequest(['name' => 'Ana'])); echo $reply->getGreeting();
Routing
Connect::service() adds one route per method of each generated
<Service>Interface the handler implements:
| Method | Route |
|---|---|
| Any unary or server-streaming method | POST <prefix>/<package>.<Service>/<Method> |
Methods with option idempotency_level = NO_SIDE_EFFECTS; |
also GET (and HEAD) on the same URI |
| Client-streaming and bidirectional methods | POST, answering unimplemented |
The routes are ordinary Laravel routes, so everything you know applies:
// routes/api.php: the "api" prefix and middleware group apply. Connect::service(GreetHandler::class); // Route middleware, as for any route. Connect::service(AccountHandler::class)->middleware(['auth:sanctum', 'throttle:60,1']); // Groups, prefixes and names. Route::prefix('rpc')->middleware('auth:sanctum')->group(function () { Connect::service(GreetHandler::class)->name('greet.'); // greet.Greet, greet.GreetMany Connect::service(AdminHandler::class)->withoutMiddleware('throttle:api'); }); // A handler implementing several services, served only for one of them: Connect::service(BigHandler::class, \Greet\V1\GreetServiceDescriptor::class);
- The routes point at a controller (
ConnectController) with the service and method stored as route data, never at a closure, sophp artisan route:cacheandphp artisan route:listwork. - CSRF protection (
VerifyCsrfToken,ValidateCsrfToken,PreventRequestForgery) is removed from Connect routes: RPC clients do not send CSRF tokens. If you serve Connect routes fromroutes/web.phpwith cookie sessions, protect them another way (a custom header the browser must send,SameSitecookies, CORS). - Requests reach the handler only after the route middleware ran, so
auth,can,throttleand your own middleware work. Their errors come back in the protocol of the call (see Errors). - The handler is resolved from the container for each call, so constructor injection works.
- Laravel's global middleware (
TrimStrings,ConvertEmptyStringsToNull) does not touch RPC messages: the server reads the raw body and the raw query string.
The Context
Every method gets the message and a Wargasipil\ConnectRpc\Context:
| Method | What it gives |
|---|---|
request() |
The Laravel Illuminate\Http\Request |
user(?string $guard = null) |
$request->user($guard) |
header(string $name), headerValues(), headers() |
Request headers (lowercase names) |
binaryHeader(string $name) |
A decoded -bin header |
protocol() |
Protocol::Connect or Protocol::GrpcWeb |
codec() |
"proto" or "json" |
method() |
The MethodDescriptor being called |
timeoutMs(), deadline(), remainingMs(), deadlineExceeded() |
The client's timeout as a deadline |
setResponseHeader(), addResponseHeader() |
Response headers (-bin values are base64-encoded for you) |
setResponseTrailer(), addResponseTrailer() |
Response trailers |
public function greet(GreetRequest $request, Context $ctx): GreetResponse { $locale = $ctx->header('x-locale') ?? 'en'; $ctx->setResponseHeader('x-served-by', gethostname()); foreach ($this->slowSteps() as $step) { if ($ctx->deadlineExceeded()) { throw new ConnectException(Code::DeadlineExceeded, 'took too long'); } $step(); } // ... }
The server also checks the deadline when the handler returns and before
each streamed message, and answers deadline_exceeded once it has passed.
PHP cannot stop a running handler, so check deadlineExceeded() in long
loops.
Errors
Throw a ConnectException with a Code:
use App\Proto\ErrorInfo; // any protobuf message can be a detail, such as google.rpc.ErrorInfo use Wargasipil\ConnectRpc\Code; use Wargasipil\ConnectRpc\ConnectException; throw new ConnectException(Code::NotFound, 'no such user'); throw (new ConnectException(Code::FailedPrecondition, 'account is locked')) ->withDetail(new ErrorInfo(['reason' => 'LOCKED', 'domain' => 'example.com'])) ->withMetadata('x-retry-after', '30');
Clients see the code, the message, the details and the metadata. In
connect-go: connect.CodeOf(err), err.Details(); in connect-web:
ConnectError.code, findDetails().
Laravel's exceptions are mapped for you, whether a handler or a route middleware throws them:
| Exception | Code |
|---|---|
ConnectException |
its own code, message, details and metadata |
ValidationException |
invalid_argument, message "field: error; field: error" |
AuthenticationException (the auth middleware) |
unauthenticated |
AuthorizationException (can, Gate::authorize) |
permission_denied (not_found for denyAsNotFound()) |
ModelNotFoundException (findOrFail), RecordsNotFoundException |
not_found |
ThrottleRequestsException (the throttle middleware) |
resource_exhausted, with retry-after metadata |
Other HttpException (abort()) |
by status, as the Connect spec maps HTTP statuses: 400 internal, 401 unauthenticated, 403 permission_denied, 404 unimplemented, 429/502/503/504 unavailable, others unknown. Prefer a ConnectException in handlers. |
| Anything else | internal, with the message "internal error" unless debug is on |
Unexpected exceptions are reported to Laravel's exception handler (your
logs, Sentry, ...) as usual; ConnectException and the client errors above
are not.
All 16 codes: canceled, unknown, invalid_argument,
deadline_exceeded, not_found, already_exists, permission_denied,
resource_exhausted, failed_precondition, aborted, out_of_range,
unimplemented, internal, unavailable, data_loss, unauthenticated.
In PHP they are the cases of the Code enum (Code::InvalidArgument, ...).
Requests the server cannot serve get these answers, as in connect-go:
| Situation | Answer |
|---|---|
Wrong HTTP method (GET on a method without NO_SIDE_EFFECTS) |
HTTP 405 |
Unknown Content-Type, or plain gRPC (application/grpc) |
HTTP 415 |
| Bad message, bad envelope, bad timeout, missing GET parameters | invalid_argument |
Message bigger than max_message_size (also after decompression) |
resource_exhausted |
| Unknown compression | unimplemented |
| Unknown method of a known service | HTTP 404 (Laravel's), which clients read as unimplemented |
Server streaming
Return or yield the messages. Each one is sent and flushed as soon as it is yielded:
public function watchOrders(WatchOrdersRequest $request, Context $ctx): iterable { $ctx->setResponseHeader('x-shop', $request->getShopId()); // before the first yield foreach (Order::where('shop_id', $request->getShopId())->cursor() as $order) { yield new OrderEvent(['id' => $order->id, 'status' => $order->status]); } $ctx->setResponseTrailer('x-count', '42'); // sent at the end }
- Headers set before the first
yieldare sent. To send them before a slow first message,yield null;first. - A
ConnectExceptionthrown before the first message is a normal error response; thrown later, it ends the stream with that error (in the end-of-stream message, or the gRPC-Web trailers frame). - An array or any iterable works too:
return [$a, $b];. - The response is a Laravel
StreamedResponsewithX-Accel-Buffering: noandCache-Control: no-cache, and the package flushes PHP's output buffers after each message. Read Shared hosting before relying on streams in production. - A stream holds one PHP worker for as long as it runs.
gRPC-Web and browsers
The same routes answer gRPC-Web, so @connectrpc/connect-web with either
transport works, as do grpc-web clients:
import { createClient } from "@connectrpc/connect"; import { createConnectTransport, createGrpcWebTransport } from "@connectrpc/connect-web"; import { GreetService } from "./gen/greet/v1/greet_pb"; const transport = createConnectTransport({ baseUrl: "https://api.example.com/api" }); // or: createGrpcWebTransport({ baseUrl: "https://api.example.com/api" }) const client = createClient(GreetService, transport); const { greeting } = await client.greet({ name: "Ana" });
gRPC-Web puts the status in a trailers frame at the end of the body (or in
the headers, for errors before any message), so it needs no HTTP trailers and
works over HTTP/1.1. application/grpc-web-text (base64) is supported for
clients that need it.
CORS
Browsers on another origin need CORS. Use Laravel's config/cors.php
(php artisan config:publish cors): add the paths of your Connect routes and
allow and expose the protocol headers:
// config/cors.php return [ 'paths' => ['api/*'], 'allowed_methods' => ['GET', 'POST'], 'allowed_origins' => ['https://app.example.com'], 'allowed_headers' => [ 'Content-Type', 'Accept', 'Authorization', 'Connect-Protocol-Version', 'Connect-Timeout-Ms', 'Connect-Content-Encoding', 'Connect-Accept-Encoding', 'Grpc-Timeout', 'Grpc-Encoding', 'Grpc-Accept-Encoding', 'X-Grpc-Web', 'X-User-Agent', // plus your own request headers ], 'exposed_headers' => [ 'Grpc-Status', 'Grpc-Message', 'Grpc-Status-Details-Bin', 'Grpc-Encoding', 'Connect-Content-Encoding', 'Content-Encoding', // plus your own response headers and trailers, e.g. 'Trailer-X-Count' ], 'max_age' => 7200, 'supports_credentials' => false, ];
Unary Connect calls send trailers as Trailer-<name> headers, so expose
those too if the browser must read them.
Typed clients
The generated <Service>Client calls any Connect server (this package,
connect-go, connect-es, ...) with Laravel's HTTP client:
use Greet\V1\GreetManyRequest; use Greet\V1\GreetRequest; use Greet\V1\GreetServiceClient; use Wargasipil\ConnectRpc\Client\CallOptions; use Wargasipil\ConnectRpc\Client\ClientOptions; use Wargasipil\ConnectRpc\ConnectException; $client = new GreetServiceClient('https://api.example.com/api', new ClientOptions( codec: 'proto', // or 'json' gzipRequests: true, // gzip request bodies of 1 KB or more timeoutMs: 5_000, // sent as Connect-Timeout-Ms, and enforced locally headers: ['authorization' => 'Bearer '.$token], )); try { $reply = $client->greet(new GreetRequest(['name' => 'Ana']), new CallOptions( headers: ['x-request-id' => (string) Str::uuid()], timeoutMs: 1_000, onHeader: fn (array $headers) => logger()->debug('headers', $headers), onTrailer: fn (array $trailers) => logger()->debug('trailers', $trailers), )); } catch (ConnectException $e) { report($e); // $e->code(), $e->rawMessage(), $e->details(), $e->metadata() } // Server streams are read as the messages arrive, not buffered whole. $stream = $client->greetMany(new GreetManyRequest(['name' => 'Ana', 'count' => 3])); foreach ($stream as $message) { echo $message->getGreeting(), "\n"; } $stream->trailers(); // after the loop // $stream->close() stops reading early.
ClientOptions |
Default | |
|---|---|---|
codec |
'proto' |
'proto' or 'json' |
gzipRequests |
false |
Compress request bodies of at least compressMinBytes (1024) |
acceptGzip |
true |
Ask for gzip responses |
timeoutMs |
null |
Default timeout of every call |
headers |
[] |
Headers of every call (-bin names: raw bytes, base64-encoded for you) |
maxResponseBytes |
0 |
Largest response message (after decompression); 0 for no limit |
useGet |
false |
Call NO_SIDE_EFFECTS methods with GET, so HTTP caches can help |
httpOptions |
[] |
Extra Guzzle options (proxy, verify, ...) |
Every failure is a ConnectException: the server's error, unavailable
for network errors, deadline_exceeded when the timeout passes, unknown
or internal for responses that are not valid Connect responses. The
client speaks the Connect protocol only (not gRPC-Web).
Configuration
php artisan vendor:publish --tag=connect-config
// config/connect.php return [ // Largest request message (unary body or one stream message), checked as // it arrives and again after decompression. resource_exhausted if bigger. 'max_message_size' => env('CONNECT_MAX_MESSAGE_SIZE', 4 * 1024 * 1024), // Hard cap on decompressed bytes (gzip bombs). 'max_decompressed_size' => env('CONNECT_MAX_DECOMPRESSED_SIZE', 4 * 1024 * 1024), // Show real messages of unexpected exceptions to clients. null: APP_DEBUG. 'debug' => env('CONNECT_DEBUG'), ];
PHP's post_max_size and your web server's body limit apply before these.
Shared hosting
The package is pure PHP and starts no processes, so it deploys like any
Laravel app, including to cheap shared hosting (zip with vendor/, no SSH,
no extra extensions):
- Unary calls and gRPC-Web are plain HTTP POSTs (and GETs). They work anywhere Laravel works, behind any proxy or CDN.
- Server streams hold one PHP worker each for as long as they run. Shared plans have few workers; long or many streams can starve your site.
- Some hosts buffer responses. LiteSpeed, nginx or a CDN in front of PHP
may hold a stream's messages and send them all at the end. The package
sends
X-Accel-Buffering: noand flushes PHP's output buffers after every message, which is enough on most servers, but verify on your host: call a stream that yields slowly and check the messages arrive one by one (curl -Nshows it). If they don't, use unary calls (or polling) there. ext-zlib(gzip) is on almost every host; without it, calls still work, uncompressed.ext-protobufis optional; the pure-PHPgoogle/protobufis used without it.- Generate code on your machine and deploy the generated files; the plugin never runs on the server.
Testing your services
A Connect unary call with JSON is a JSON POST, so Laravel's HTTP tests work as they are:
public function test_greet(): void { $this->postJson('/api/greet.v1.GreetService/Greet', ['name' => 'Ana']) ->assertOk() ->assertJson(['greeting' => 'Hello, Ana!']); $this->postJson('/api/greet.v1.GreetService/Greet', ['name' => '']) ->assertStatus(400) ->assertJson(['code' => 'invalid_argument']); }
actingAs(), withoutMiddleware() and the rest work too.
To test code that uses a generated client, fake the responses with
Http::fake() and the ConnectFake helpers:
use Illuminate\Http\Client\Request; use Illuminate\Support\Facades\Http; use Wargasipil\ConnectRpc\Code; use Wargasipil\ConnectRpc\Testing\ConnectFake; Http::fake([ '*/greet.v1.GreetService/Greet' => ConnectFake::response(new GreetResponse(['greeting' => 'Hi'])), '*/greet.v1.GreetService/GreetMany' => ConnectFake::stream([ new GreetResponse(['greeting' => 'one']), new GreetResponse(['greeting' => 'two']), ]), '*/billing.v1.BillingService/*' => ConnectFake::error(Code::Unavailable, 'try later'), ]); // ... run the code under test ... Http::assertSent(fn (Request $request) => str_ends_with($request->url(), '/greet.v1.GreetService/Greet'));
ConnectFake::response() and stream() take the codec your client uses
('proto' by default).
Example app
example/ has a proto, its generated code, a handler, a routes
file and a script that calls it:
composer install php -S 127.0.0.1:8080 example/server.php php example/client.php http://127.0.0.1:8080/api
See example/README.md.
What it does not do
- Client-streaming and bidirectional methods. PHP receives the whole
request body before your code runs, so the server answers
unimplemented. The plugin leaves them out of the interface and the client. - Plain gRPC (
application/grpc). It needs HTTP/2 trailers, which PHP behind a web server cannot send. gRPC clients can use gRPC-Web, or Connect. - gRPC-Web in the PHP client. The client speaks Connect.
- Cancelling a client call from outside. PHP's HTTP calls block; use a
timeout. Closing a server stream (
$stream->close()) stops reading. - Interceptors. Use Laravel middleware for the server, and Laravel HTTP
client features (
Http::globalRequestMiddleware()) for the client. - Other compressions (br, zstd, ...): gzip only.
Compatibility
- PHP 8.2, 8.3, 8.4 (Laravel 13 needs 8.3).
- Laravel 11, 12 and 13 (
illuminate/*components). Laravel 11's security support has ended and every 11.x release has open advisories, so Composer 2.10+ refuses to install it unless advisory blocking is off (COMPOSER_POLICY_ADVISORIES_BLOCK=0orconfig.policy.advisories). This package's CI tests Laravel 11 that way. google/protobuf4.30 or newer (including 5.x), with or withoutext-protobuf.- The plugin needs only PHP and Composer's autoloader. It is tested with
protoc36 andbuf1.57; generated code follows Google's PHP generator naming of protobuf 36. - Clients and servers tested against: connect-go 1.19 (Connect, Connect with JSON, GET, gzip, gRPC-Web) and the Connect conformance suite 1.0.7.
- HTTP/1.1 and HTTP/2 between the client and your web server both work; nothing depends on HTTP/2.