Download the PHP package oybek-daniyarov/laravel-trpc without Composer
On this page you can find all versions of the php package oybek-daniyarov/laravel-trpc. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download oybek-daniyarov/laravel-trpc
More information about oybek-daniyarov/laravel-trpc
Files in oybek-daniyarov/laravel-trpc
Package laravel-trpc
Short Description End-to-end type-safe APIs for Laravel. Like tRPC, but for Laravel + TypeScript.
License MIT
Homepage https://github.com/oybek-daniyarov/laravel-trpc
Informations about the package laravel-trpc
Laravel tRPC
Generate a fully typed TypeScript client from your Laravel routes — with request types, response types, and optional React Query/Inertia helpers.
Quick Example
What This Is (and Isn't)
What it is: A Laravel-first generator that inspects your routes and produces a TypeScript client with fully typed inputs and outputs.
What it isn't: This is not a server-side implementation of the tRPC protocol. It doesn't require a Node.js tRPC router. It generates a typed HTTP client for your existing Laravel routes.
Runtime model: Generation happens at build time via php artisan trpc:generate. The output is a small TypeScript client that calls your HTTP endpoints — no runtime reflection on the PHP side.
Status
Beta (0.x). The public API and generated output structure may change between minor versions. For production use:
- Pin to exact versions in
composer.json - Review generated output diffs on upgrade
- Follow the CHANGELOG for breaking changes
Features
- Full Type Safety: Request bodies, responses, URL parameters, and query strings are all typed
- Zero Runtime Overhead: Types are generated at build time, no runtime reflection
- Framework Integrations: Built-in support for React Query and Inertia.js
- Grouped API Client: Object-based API (
api.users.show()) with full autocomplete - Postman Export: Generate Postman collections from your routes
Example Project
See it in action — a Laravel API with Inertia.js frontend, fully typed end-to-end:
🔗 github.com/oybek-daniyarov/empty-space
Table of Contents
- Example Project
- Requirements
- Installation
- Quick Start
- TypedRoute Attribute
- Generate & Use
- Generated Files
- Output Contract
- Configuration
- Middleware & Authentication
- Error Handling
- Type Helpers
- React Query Integration
- Inertia.js Integration
- API Client Configuration
- Command Options
- Customizing Stubs
- Known Limitations
- Troubleshooting
- Versioning
- Backstory
Requirements
- PHP 8.3+
- Laravel 11.x or 12.x
- spatie/laravel-data
- spatie/laravel-typescript-transformer
Installation
Publish the config file:
Quick Start
1. Define Data Classes
2. Add TypedRoute Attribute to Controllers
TypedRoute Attribute
The #[TypedRoute] attribute explicitly declares request and response types for your API endpoints. When applied, it takes priority over static analysis for type detection.
Parameters
| Parameter | Type | Description |
|---|---|---|
request |
class-string\|null |
Request body Data class (for POST/PUT/PATCH) |
query |
class-string\|null |
Query parameters Data class (for GET requests) |
response |
class-string\|null |
Response Data class |
errorResponse |
class-string\|null |
Error response Data class (defaults to ValidationError) |
isCollection |
bool |
Response is an array of items (Array<T>) |
isPaginated |
bool |
Response is paginated (PaginatedResponse<T>) |
Examples
Basic response type:
Request and response types:
Query parameters (for GET with filters/search):
Paginated response:
Collection response (non-paginated array):
No response body (204 No Content):
Custom error response:
Query vs Request
- Use
requestfor body data (POST, PUT, PATCH requests) - Use
queryfor URL query parameters (GET requests with filters, search, pagination)
Generate & Use
Generate TypeScript Client
4. Use in TypeScript
Generated Files
The generator produces a tree-shakeable folder structure:
Tree-Shaking
Import only what you need for optimal bundle size:
Output Contract
The generator produces a stable folder structure:
Naming Conventions
- Route names map directly to TypeScript keys:
users.index→api.users.index() - Groups are derived from the first segment of the route name
- Parameters use Laravel's route parameter names:
{user}→{ user: number }
Configuration
Configuration Reference
| Option | Type | Default | Description |
|---|---|---|---|
output_path |
string | resource_path('js/api') |
Directory for generated TypeScript files |
api_prefix |
string | 'api' |
API route prefix for filtering |
version |
string | 'v1' |
API version identifier |
route_mode |
string | 'api' |
Route collection mode (see below) |
include_patterns |
array | [] |
Route patterns to include |
exclude_patterns |
array | [...] |
Route patterns to exclude |
exclude_methods |
array | ['options', 'head'] |
HTTP methods to skip |
preset |
string|null | null |
Framework preset: 'inertia', 'api', 'spa' |
outputs |
array | [...] |
Files to generate |
auto_typescript_transform |
bool | true |
Auto-run typescript:transform |
laravel_types_path |
string|null | null |
Path to laravel.d.ts |
Route Modes
| Mode | Description |
|---|---|
'api' |
Only routes starting with api_prefix (default) |
'web' |
Only routes NOT starting with api_prefix |
'all' |
All routes (use with include/exclude patterns) |
'named' |
Only routes with names |
'attributed' |
Only routes with #[TypedRoute] attribute |
Presets
Use presets to quickly enable common output configurations:
| Preset | Enables | Use Case |
|---|---|---|
'inertia' |
Core files + Inertia helpers | Laravel + Inertia.js apps |
'api' |
Core files + React Query + Mutations | API-first / SPA with React Query |
'spa' |
Core files + Inertia + React Query + Mutations | Full-featured SPA |
null |
Custom (configure outputs manually) |
Fine-grained control |
Presets override the outputs array. To customize individual outputs, set preset to null and configure outputs directly.
Postman Configuration
Middleware Configuration
Control how middleware appears in the generated TypeScript output:
Before (with short_names: false and no exclusions):
After (with short_names: true and Tenancy excluded):
| Middleware Input | Short Name Output |
|---|---|
Stancl\Tenancy\Middleware\InitializeTenancyByDomain |
InitializeTenancyByDomain |
App\Http\Middleware\RateLimiter:api |
RateLimiter:api |
auth:sanctum |
auth:sanctum (unchanged) |
web |
web (unchanged) |
Middleware & Authentication
The generated routes include middleware information, allowing you to build auth-aware UIs.
Generated Route Data
Each route includes middleware and authentication info:
Type Helpers for Auth Routes
Filter routes by authentication requirement:
Checking Auth Before API Calls
Accessing Middleware Array
Error Handling
Built-in Error Types
The generated types.ts includes standard Laravel error types:
Custom Error Types with errorResponse
Define custom error Data classes for specific routes:
Using Error Types in TypeScript
Error Handling with React Query
Type Helpers
Extract types from route names for use in your components:
React Query Integration
Enable in config:
Generated Files
| File | Description |
|---|---|
react-query.ts |
Low-level utilities: queryKey, createQueryOptions, createInfiniteQueryOptions |
queries.ts |
Resource-based query factories organized by API resource (e.g., usersQueries, postsQueries) |
mutations.ts |
Resource-based mutation factories organized by API resource (e.g., usersMutations, postsMutations) |
Setup
Before using queries and mutations, create configured instances in a setup file:
Then import from your setup file in components:
Resource-Based Queries (queries.ts)
The queries.ts file generates query factories for each API resource, providing:
- Pre-configured
queryOptions()andinfiniteQueryOptions()for each GET endpoint - Type-safe query keys with
keysobject for cache management - Automatic infinite query support for paginated endpoints
Low-Level Utilities (react-query.ts)
For more control, use the low-level utilities:
Full Example
Infinite Queries for Pagination
Paginated endpoints automatically generate infiniteQueryOptions:
Resource-Based Mutations (mutations.ts)
The mutations.ts file generates type-safe mutation factories for POST, PUT, PATCH, and DELETE endpoints:
Mutation keys for cache management:
Inertia.js Integration
API Client Configuration
Basic Setup
Create a configured API instance and export it for use throughout your app:
Usage
Per-Request Options
All API methods accept an optional RequestOptions object as the last parameter:
Next.js App Router
Server Components
Server Actions
Route Handlers
React Query Integration
With Configured API (Recommended)
Use createQueries to bind queries to a configured API instance:
Command Options
Command Options Reference
| Option | Description |
|---|---|
--output=PATH |
Override the output directory from config |
--api-prefix=PREFIX |
Override the API route prefix filter |
--skip-typescript-transform |
Skip auto-running typescript:transform |
--postman |
Generate Postman collection only (shorthand for --format=postman) |
--postman-env |
Also generate Postman environment file |
--format=FORMAT |
Output format: typescript (default), postman, or all |
--force |
Overwrite existing files without confirmation |
--base-url=URL |
Set default base URL for the generated TypeScript client |
Customizing Stubs
Publish the stub templates:
Templates will be copied to resources/views/vendor/trpc/.
Known Limitations
- Route model binding: Parameters are typed as
number | stringby default. Custom types require explicit#[TypedRoute]configuration. - Union/polymorphic responses: Not automatically detected. Use a single response Data class or document via
#[TypedRoute(response: ...)]. - Middleware inference: Auth detection relies on common middleware names (
auth,auth:*). Custom auth middleware may not be detected. - Closure routes: Routes without controller methods cannot have types extracted automatically.
Troubleshooting
"No API routes found"
- Ensure your routes use the configured
api_prefix(default:api) - Check that routes are registered before running the command
- Try
php artisan route:listto verify routes exist
Generated types are unknown
- Add
#[TypeScript]attribute to your Data classes - Run
php artisan typescript:transformfirst - Check that
laravel.d.tsexists in your output directory
TypeScript errors after regeneration
- Clear your TypeScript cache:
rm -rf node_modules/.cache - Ensure your
tsconfig.jsonincludes the output directory - Check for circular dependencies in your Data classes
Route names are duplicated
- The generator appends
_1,_2suffixes for duplicate names - Use unique route names or configure
route_name_mappingsin config
Versioning
This package follows Semantic Versioning:
- Patch (0.1.x): Bug fixes, no changes to generated output shape
- Minor (0.x.0): New features, may add fields to generated output
- Major (x.0.0): Breaking changes to generated output structure or API
During the 0.x beta period, minor versions may include breaking changes. These will be clearly documented in the CHANGELOG.
Backstory
I built this to solve a real problem: getting a strongly typed TypeScript client from Laravel routes without manual type duplication.
I used AI tooling (Claude Code) to accelerate development — it helped with boilerplate, iteration, and exploration. The architecture and direction were mine; the implementation was collaborative.
The package has 250+ passing tests, PHPStan level 8 analysis, and is used in production projects. I'm sharing it because it works and saves time.
Found a bug? Open an issue. I'll fix it.
License
MIT License. See LICENSE for details.
Credits
- Oybek Daniyarov
- Claude by Anthropic — the AI that wrote the code
- Spatie for laravel-data and typescript-transformer
- Laravel team for Wayfinder, which inspired some of the thinking here
All versions of laravel-trpc with dependencies
laravel/framework Version ^11.0|^12.0|^13.0
laravel/ranger Version 0.1.*
laravel/surveyor Version 0.1.*
spatie/laravel-data Version ^4.0
spatie/laravel-typescript-transformer Version ^3.0