lomkit/laravel-rest-api
| Install | |
|---|---|
composer require lomkit/laravel-rest-api |
|
| Latest Version: | v3.5.0 |
| PHP: | ^8.3 |
| Laravel: | 13 |
| Older releases: | 8 – 12 |
| License: | MIT |
| Last Updated: | Nov 20, 2026 |
| Links: | GitHub · Packagist |

Documentation · Upgrade from 2.x
Laravel Rest Api
Describe a model once. Get a complete API.
Write one resource class for an Eloquent model. Laravel Rest Api turns it into search, mutate, action, metric, details and delete endpoints. Your policies authorize every request, your frontend gets a rich query language, and Scramble gets a typed OpenAPI document.
No controller methods to write, no query parsing to maintain.
- One class, every endpoint: search, batch writes, custom actions, metrics, soft deletes.
- A search grammar for filters, nested groups, relations, scopes, includes, aggregates and text search.
- Laravel policies everywhere: every resource a request reaches, every row it writes.
- Built for frontends: a
detailsendpoint, per-row abilities, Precognition, precise422messages. - Documented for you: an OpenAPI document with typed schemas and examples, through Scramble.
Documentation
The full guide lives on the documentation site: installation, every endpoint, configuration and recipes. Coming from 2.x? Read the upgrade guide.
For AI assistants, the site serves llms.txt and llms-full.txt, and the package ships a Laravel Boost skill: see Use with AI.
Requirements
PHP 8.3+ and Laravel 13.30+.
From model to API
Take a Show model with a stage() relation and an artists() relation whose pivot holds a role.
1. Install the package.
composer require lomkit/laravel-rest-api
2. Describe what the API exposes. Only what you declare exists for the client. php artisan rest:resource ShowResource --model=Show scaffolds the class, and StageResource and ArtistResource follow the same pattern.
namespace App\Rest\Resources;
use App\Models\Show;
use Lomkit\Rest\Fields\Date;
use Lomkit\Rest\Fields\ID;
use Lomkit\Rest\Fields\Integer;
use Lomkit\Rest\Fields\Text;
use Lomkit\Rest\Relations\BelongsTo;
use Lomkit\Rest\Relations\BelongsToMany;
class ShowResource extends Resource
{
public static string $model = Show::class;
public function fields(): array
{
return [
ID::make('id'),
Text::make('title')->rules('max:80')->creationRules('required'),
Text::make('status'),
Integer::make('seats')->rules('min:0'),
Date::make('starts_on')->creationRules('required'),
];
}
public function relations(): array
{
return [
BelongsTo::make('stage', StageResource::class),
BelongsToMany::make('artists', ArtistResource::class)
->pivotFields([Text::make('role')->nullable()]),
];
}
}
3. Bind it to a route. The controller is one line, and your ShowPolicy authorizes every request (php artisan rest:policy ShowPolicy --model=Show writes a starting point).
class ShowsController extends Controller
{
public static string $resource = ShowResource::class;
}
// routes/api.php
use App\Rest\Controllers\ShowsController;
use Lomkit\Rest\Facades\Rest;
Rest::resource('shows', ShowsController::class)->middleware('auth:sanctum');
4. Ask.
POST /api/shows/search
{
"search": {
"filters": [{"field": "seats", "operator": ">=", "value": 500}],
"sorts": [{"field": "starts_on"}],
"includes": [{"relation": "stage"}],
"gates": ["update"]
}
}
{
"current_page": 1,
"data": [
{
"id": 2,
"title": "Opening night",
"status": "planned",
"seats": 1200,
"starts_on": "2026-07-03",
"gates": {"authorized_to_update": {"allowed": true, "message": null}},
"stage": {"id": 1, "name": "Main stage"}
},
{
"id": 3,
"title": "Late night jazz",
"status": "sold_out",
"seats": 650,
"starts_on": "2026-07-04",
"gates": {"authorized_to_update": {"allowed": true, "message": null}},
"stage": {"id": 1, "name": "Main stage"}
}
],
"from": 1,
"last_page": 1,
"per_page": 50,
"to": 2,
"total": 2,
"meta": {}
}
Each row says whether the user may update it, so the frontend knows which buttons to show.
In a hurry?
php artisan rest:quick-startasks which models to expose, then writes their resources (fields and relations read from the tables), controllers, starter policies and routes.
One resource, every endpoint
Rest::resource('shows', ShowsController::class) registers:
| Route | Endpoint | What it does |
|---|---|---|
GET /api/shows |
details | Describes the resource for the current user: fields, rules, relations, actions, metrics, abilities |
POST /api/shows/search |
search | Filters, sorts, includes, aggregates, text search, pagination |
POST /api/shows/mutate |
mutate | Creates and updates rows and their relations, in one transaction |
POST /api/shows/actions/{action} |
operate | Runs a custom action on the rows a search matches, on listed ids, or on none |
POST /api/shows/metrics/{metric} |
metric | Computes a value, trend, partition, progress or table |
DELETE /api/shows |
destroy | Deletes rows (soft deletes when the model uses them) |
POST /api/shows/restore |
restore | Restores soft deleted rows, with ->withSoftDeletes() on a model that uses SoftDeletes |
DELETE /api/shows/force |
forceDestroy | Deletes rows for good, with ->withSoftDeletes() on a model that uses SoftDeletes |
GET /api/shows/actions/{action}/batches/{batch} |
batch | Progress of a queued batch, with ->withBatchProgress() |
only(), except(), names(), middleware() and middlewareFor() shape the routes like any Laravel route.
Search: ask for exactly what the screen needs
One body combines text search, scopes, nested filters, filters through relations, aggregates and the sorts on them, includes and selects.
{
"search": {
"text": {"value": "night"},
"scopes": [{"name": "upcoming"}],
"filters": [
{"field": "seats", "operator": ">=", "value": 500},
{"nested": [
{"field": "stage.name", "value": "Main stage"},
{"field": "artists.name", "operator": "like", "value": "The%", "type": "or"}
]}
],
"aggregates": [{"relation": "artists", "type": "count"}],
"sorts": [{"field": "artists_count", "direction": "desc"}],
"selects": [{"field": "title"}],
"includes": [{"relation": "artists", "selects": [{"field": "name"}]}]
}
}
The response
{
"current_page": 1,
"data": [
{
"title": "Late night jazz",
"artists_count": 3,
"artists": [
{"name": "Ada Moon", "pivot": {"role": "support"}},
{"name": "Kofi Brass", "pivot": {"role": "headliner"}},
{"name": "Nina Volt", "pivot": {"role": "guest"}}
],
"@more": []
},
{
"title": "Opening night",
"artists_count": 2,
"artists": [
{"name": "The Lumens", "pivot": {"role": "support"}},
{"name": "Nina Volt", "pivot": {"role": "headliner"}}
],
"@more": []
}
],
"from": 1,
"last_page": 1,
"per_page": 50,
"to": 2,
"total": 2,
"meta": {}
}
@more lists the includes that hold more rows than they returned.
This search uses two more declarations on the resource: Scope::make('upcoming') in scopes(), and Contains::make() in text() with ->searchable() on the title field.
- Filters take the operators of their field type,
and/or, nested groups, dotted paths through relations (stage.name) and relation groups ({"relation": "artists", "exists": false}). - Includes take their own filters, sorts, selects, aggregates, limit and includes, and an
aliasto load one relation twice. - Text search runs on
LIKE(Contains), the full-text index of MySQL, MariaDB or PostgreSQL (FullText), or a Laravel Scout engine such as Meilisearch, Typesense or Algolia (ScoutEngine). - Instructions add your own query logic, with typed and validated fields.
- Outside HTTP,
Rest::search(ShowResource::class)->as($user)->payload($saved)->lazy()replays a saved search in a job or an export, with the same validation and policies.
Mutate: write a whole graph in one request
{
"mutate": [
{
"operation": "create",
"attributes": {"title": "Closing night", "seats": 800, "starts_on": "2026-07-05"},
"relations": {
"stage": {"operation": "attach", "key": 1},
"artists": [
{"operation": "attach", "key": 4, "pivot": {"role": "headliner"}},
{"operation": "create", "attributes": {"name": "Echo Park"}}
]
}
}
]
}
{"operations": [{"operation": "create", "key": 4, "relations": {"stage": {"operation": "attach", "key": 1}, "artists": [{"operation": "attach", "key": 4}, {"operation": "create", "key": 5}]}}]}
Every entry is validated by the rules of its fields and checked against the policies before the first write, then everything runs in one transaction. An Enum field can offer only some of its cases to writes, ->offered([...]), so a withdrawn status stays readable and filterable on old rows. Relation entries also take attach and detach, plus sync and toggle on many-to-many relations and delete on child rows, and a relation can limit them with onlyOperations() and withoutOperations(). Add a response block to get the written rows back, and versioned() on the resource to answer 409 when a row changed since the client read it.
A write can ask first: when mutateConfirmation() on the resource (or destroyConfirmation(), restoreConfirmation(), forceDestroyConfirmation()) returns a Confirmation, the request answers 428 with a signed token and writes nothing, and the same body sent back with "confirmation": "<token>" runs it.
A mistake comes back on its exact key. Here, an entry without title, with "seats": -3 and a created_at:
{
"message": "The mutate.0.attributes.title field is required. (and 2 more errors)",
"errors": {
"mutate.0.attributes.title": ["The mutate.0.attributes.title field is required."],
"mutate.0.attributes.seats": ["The mutate.0.attributes.seats field must be at least 0."],
"mutate.0.attributes": ["The created_at key of the mutate.0.attributes field is not writable on create."]
}
}
Actions: your business operations, as endpoints
class CancelShows extends Action
{
public function fields(): array
{
return [Text::make('reason')->rules('required')];
}
public function authorizeEach(): ?string
{
return 'update';
}
public function handle(ActionFields $fields, Collection $models): void
{
foreach ($models as $show) {
$show->update(['status' => 'cancelled']);
}
}
public function respond(ActionFields $fields, int $impacted): ?ActionResponse
{
return ActionResponse::message("{$impacted} shows cancelled: {$fields->reason}");
}
}
Declare it in the resource's actions(), and it runs on the rows of a search, once the policy lets the user update each of them:
POST /api/shows/actions/cancel-shows
{
"fields": [{"name": "reason", "value": "Storm warning"}],
"search": {"filters": [{"field": "stage.name", "value": "Main stage"}]}
}
{"data": {"impacted": 2, "result": {"type": "message", "message": "2 shows cancelled: Storm warning"}}}
The search block is required: "search": {} runs the action on every row the user may reach. Each chunk of rows runs in its own transaction: ->atomic() puts the whole run in one, and ->transactionPerRow() hands each row to handleRow() in a transaction of its own. Implement ShouldQueue to process the rows in queued chunks, and BatchableAction to run them as a batch whose progress the client can follow; the exports recipe builds a CSV download that way. An action can also target listed ids or no row at all, and ask the user to confirm before it runs.
Metrics: dashboards without extra endpoints
class ShowsByStatus extends Partition
{
public function calculate(Builder $query): PartitionResult
{
return $this->count($query, 'status');
}
}
{"data": {"type": "partition", "parts": [{"key": "planned", "label": "planned", "value": 2}, {"key": "sold_out", "label": "sold_out", "value": 1}], "other": null}}
Value, Trend, Partition, Progress and Table cover counts, sums, averages, medians and percentiles, with date ranges, time zones, the previous period and a result cache. A metric computes over the rows the client is allowed to see, and accepts the filters of a search.
And everything around it
- Authorization: your policies run
viewAnyon every resource a request reaches, before validation, andcreate,update,delete,restoreorforceDeleteon every row it writes, before the first write.perimeterQuery()scopes each resource to the rows a user may reach (a tenant, a team). - OpenAPI documentation: install Scramble and
/docs/apidocuments every endpoint, with a typed body per resource, request examples and error responses. - Details for frontends:
GET /api/shows?with=fields.filter,fields.rules,actions.authorizedtells a frontend how each field filters, which rules each form field follows, and which actions the user may run. - Precognition: live form validation with Laravel Precognition on every endpoint, once
rest.precognition.enabledis on. - Predictable limits: list sizes, nesting depths, totals, value lengths and the rows one search renders are bounded in
config/rest.php, and an oversized request answers one clear422before any query. A partition or a trend keeps its largest groups, 100 by default, and folds the rest intoother. - Translated messages: every message the package writes for a client ships in English and follows the locale of the request;
php artisan vendor:publish --tag=rest-langlets you reword them or translate them inlang/vendor/rest/<locale>. rest:checkfor CI: reports routes without authentication, models without a policy, resources that show every row (noperimeterQuery()), actions without row checks and relations that acceptdetachon a foreign key that does not accept null, and the engine searches that a restriction cannot reach, with the Scout driver of the environment it runs in (setSCOUT_DRIVERin CI as in production). It also lists the extensions, where each one comes from, and the ones it cannot build, names the extensions that restrict the rows of each resource, and runs the checks of extensions.- Extensions: one class adds behavior to every resource it applies to. The class declares its name with
name(). List the class in theextensionskey ofconfig/rest.php, or let a package register it withRest::registerExtension(AccessControlExtension::class);disabled_extensionsturns one off. An extension can restrict the rows of a resource with its own where clauses (and, withProvidesPerimeter, stand for its perimeter inrest:check), add columns, subqueries and eager loads to the rows a response renders, narrow page sizes, totals and include limits, add search instructions under its name, restrict engine searches, declare the index attributes they use (lists of strings included), bring the profile of another Scout engine, prepare the row checks of policies in bulk, add tenant or rules items to the cache keys of decisions and metric results (and shorten or drop the cache of an ability), declare gates, hide fields or make them read-only, unfilterable or unsortable for a user, add middleware to the routes of a resource, refuse a write before it is written, be notified after a write commits or after a read, add keys under its name to the meta of searches and/details, document its responses and meta in the OpenAPI document, and add checks torest:check. The package enforces each rule: a restriction holds only where clauses and cannot widen the rows, an engine restriction holds only AND-ed conditions, an added column never renders, a limit only goes down, a row preparation decides nothing and changes none of the rows it receives, a cache item never adds or lengthens a cached ability, a hidden field answers as an undeclared one, route middleware is only added, a refusal writes nothing, a write notification comes only after the commit, a read notification cannot change the response, meta keys never take a key of the package or of the resource, and a documented status never replaces another. The Boost skill describes each kind. - Generators:
rest:resource --generatereads the table, andrest:controller,rest:policy,rest:action,rest:instruction,rest:metricandrest:responsescaffold the rest. - Laravel Boost: the package ships a Boost skill with the full feature reference.
Contributing
Contributions are welcome. Read the contributing guide first.
License
Laravel Rest Api is open-source software licensed under the MIT license.
Related Packages
A boilerplate package for BREAD operations through REST API in Laravel
Version History
| Version | Released | PHP | Laravel | License |
|---|---|---|---|---|
| v3.5.0 | ^8.3 | ^13.30 | MIT | |
| v3.4.0 | ^8.3 | ^13.30 | MIT | |
| v3.3.0 | ^8.3 | ^13.30 | MIT | |
| v3.2.3 | ^8.3 | ^13.30 | MIT | |
| v3.2.2 | ^8.3 | ^13.30 | MIT | |
| v3.2.1 | ^8.3 | ^13.30 | MIT | |
| v3.2.0 | ^8.3 | ^13.30 | MIT | |
| v3.1.1 | ^8.3 | ^13.30 | MIT | |
| v3.1.0 | ^8.3 | ^13.30 | MIT | |
| v3.0.1 | ^8.3 | ^13.30 | MIT | |
| v3.0.0 | ^8.3 | ^13.30 | MIT | |
| v2.23.2 | ^8.2 | ^12| | MIT | |
| v2.23.1 | ^8.2 | ^12| | MIT | |
| v2.23.0 | ^8.2 | ^12| | MIT | |
| v2.22.3 | ^8.2 | ^12| | MIT | |
| v2.22.2 | ^8.2 | ^12| | MIT | |
| v2.22.1 | ^8.2 | ^12| | MIT | |
| v2.22.0 | ^8.2 | ^12| | MIT | |
| v2.21.3 | ^8.2 | ^11| | MIT | |
| v2.21.2 | ^8.2 | ^11| | MIT | |
| v2.21.1 | ^8.2 | ^11| | MIT | |
| v2.21.0 | ^8.2 | ^11| | MIT | |
| v2.20.1 | ^8.2 | ^11| | MIT | |
| v2.20.0 | ^8.2 | ^11| | MIT | |
| v2.19.0 | ^8.2 | ^11| | MIT | |
| v2.18.0 | ^8.2 | ^11| | MIT | |
| v2.17.4 | ^8.2 | ^11| | MIT | |
| v2.17.3 | ^8.2 | ^11| | MIT | |
| v2.17.2 | ^8.2 | ^11| | MIT | |
| v2.17.1 | ^8.2 | ^11| | MIT |
Showing the latest 30 of 89. See every release on Packagist
Pre-releases (4)
| Version | Released | PHP | Laravel | License |
|---|---|---|---|---|
| v0.4.0-beta | ^7.3| | ^8.37| | MIT | |
| v0.3.0-beta | ^7.3| | ^8.37| | MIT | |
| v0.2.0-beta | ^7.3| | ^8.37| | MIT | |
| v0.1.0-beta | ^7.3| | ^8.37| | MIT |