Getting Started

Introduction

What Laravel Rest Api does, when it fits and when it does not, its requirements, and how it compares with API Resources, Laravel Orion and similar packages.

What it is

Laravel Rest Api turns your Eloquent models into a full API without one controller per use case. For each model, you write a resource that declares what the API exposes: its fields, its relations, its scopes, its actions and its rules. A thin controller binds the resource to a route name, and one call to Rest::resource() registers its endpoints.

app/Rest/Resources/ProductResource.php
namespace App\Rest\Resources;

use App\Models\Product;
use Lomkit\Rest\Fields\ID;
use Lomkit\Rest\Fields\Integer;
use Lomkit\Rest\Fields\Text;
use Lomkit\Rest\Relations\BelongsTo;

class ProductResource extends Resource
{
    public static string $model = Product::class;

    public function fields(): array
    {
        return [
            ID::make('id'),
            Text::make('name')->creationRules('required'),
            Integer::make('price'),
        ];
    }

    public function relations(): array
    {
        return [
            BelongsTo::make('category', CategoryResource::class),
        ];
    }
}
routes/api.php
use App\Rest\Controllers\ProductsController;
use Lomkit\Rest\Facades\Rest;

Rest::resource('products', ProductsController::class);

Clients can now search, filter, sort and paginate the products, include their category, create and update them in batches, and delete them, all inside the rules you declared.

The endpoints

Each registered resource answers on a fixed set of routes. The opt-in routes are added with withSoftDeletes() and withBatchProgress():

MethodURIEndpointPurpose
GET/api/productsdetailsDescribe the resource for the current user
POST/api/products/searchsearchFilter, sort, include, aggregate and paginate rows
POST/api/products/mutatemutateCreate and update rows and their relations in one transaction
POST/api/products/actions/{action}operateRun an action that the resource declares
POST/api/products/metrics/{metric}metricCompute a metric that the resource declares
DELETE/api/productsdestroyDelete rows
POST/api/products/restorerestoreRestore soft-deleted rows, opt-in
DELETE/api/products/forceforceDestroyForce delete rows, opt-in
GET/api/products/actions/{action}/batches/{batch}batchRead the progress of a batched action, opt-in

See Resources for the registration options.

Why use it

  • Declare, do not code. A column that a resource does not declare does not exist for clients. The same goes for relations, scopes, actions and instructions. Adding a column to a table never exposes it.
  • One request, many rows. A search reads nested relations with their own filters and limits. A mutation creates a row, attaches its tags and updates its children in one transaction.
  • Authorization built in. Every endpoint checks your Laravel policies: viewAny on each resource a request reaches, then each row it writes or deletes. A perimeter query decides which rows exist for each client. See Perimeter and Policies.
  • Typed and validated. Each field has a type that decides its filter operators, its validation and its OpenAPI schema. Every payload is validated in one pass, with exact error keys such as search.filters.0.field.
  • Bounded. Request sizes, nesting depths and totals are limited by configuration, so one request cannot ask for unbounded work. See Limits.
  • Documented. The package describes every endpoint in the OpenAPI document that Scramble serves. See OpenAPI.

How it fits Laravel

The package builds on what your application already has:

  • Eloquent: resources read and write your models, their casts, their scopes and their relations.
  • Policies: authorization goes through Gate and your policy classes. See Policies.
  • Validation: field rules are Laravel rules, and errors come back as standard 422 responses. See Validation.
  • Routing: Rest::resource() registers plain Laravel routes that work with route groups, middleware, route:list and route:cache.
  • Queues and events: actions can be queued or batched, and writes dispatch Laravel events. See Actions and Events and hooks.
  • Laravel Scout: a resource can run its text search on a Scout search engine. See Search engines.
  • Laravel Precognition: forms can validate a payload before they send it. See Precognition.

When to use it

Laravel Rest Api fits an application whose clients read and write Eloquent models: a single-page app, a mobile app, an admin panel or another service. It suits list screens that filter, sort and include relations, forms that create or update several rows at once, bulk actions and dashboards. Laravel Rest Api replaces one controller method per use case with one resource per model, and applies your Laravel validation rules and policies to every request.

When it does not fit

  • A fixed API standard. Laravel Rest Api uses its own request and response format, and sends a search as a POST request with a JSON body. When your clients expect JSON:API documents or a GraphQL schema, use a package built for that standard.
  • Endpoints that do not read or write models. A webhook receiver, a payment flow or a proxy to another service is simpler as a plain Laravel controller. An application can serve such routes next to the routes of Laravel Rest Api.
  • Caching by URL. A search is a POST request, and browsers, proxies and CDNs do not cache POST responses by URL. Public read endpoints that rely on such a cache need GET routes of their own.

Requirements

  • Laravel Rest Api 3 requires PHP 8.3 or higher and Laravel 13.30 or higher. Applications on Laravel 12 use Laravel Rest Api 2.x.
  • Its tests run on MySQL 8, PostgreSQL 16 and SQLite.
  • dedoc/scramble adds the OpenAPI document and laravel/scout adds text search on a search engine. Both are optional, see Installation.

Compared with other approaches

  • Controllers and API Resources. Laravel's API Resources transform models into JSON inside controllers that you write, along with the query, the validation and the authorization of each endpoint. Laravel Rest Api builds the endpoints from a resource declaration and runs the validation and the policy checks itself.
  • spatie/laravel-query-builder. spatie/laravel-query-builder builds Eloquent queries from the filter, sort, include and fields query parameters of a request, inside controllers that you write. Laravel Rest Api covers reads and writes from one resource declaration, and takes a search as a JSON body.
  • Laravel Orion. Laravel Orion builds a REST API on Eloquent models and relationships through its own controller classes, with search, batch operations and hooks. Laravel Rest Api declares the API of a model in a resource class with typed fields, bound to a thin controller.
  • Laravel JSON:API. Laravel JSON:API (laravel-json-api/laravel) implements the JSON:API specification with a schema per model. Choose it when your clients expect JSON:API documents: Laravel Rest Api uses its own format.

Version 3

Version 3.0 types every declaration: fields, inputs and pivot fields are objects with a type, and the search, mutate and action payloads are validated against them. If you come from 2.x, read the Upgrade guide.

Meet Lomkit

Lomkit is an organization dedicated to the Laravel community. We offer a collection of open source packages for developers, and we keep them up to date with the latest practices of the framework.

Community contributions are welcome. Explore our packages on GitHub, open an issue or send a pull request.

Next steps