Looking to hire Laravel developers? Try LaraJobs

laravel-data-api maintained by tarandaly

Description
Publish Eloquent models through the Tarandaly Data API: schema discovery, records with filters and cursors, optimistic concurrency, batches and a change feed for the Tarandaly desktop app.
Author
Last update
2026/12/06 15:37 (dev-main)
License
Downloads
1

Comments
comments powered by Disqus

Tarandaly Data API for Laravel

Tests Static analysis Packagist License

Connect your Laravel application to the Tarandaly desktop app. You publish the Eloquent models you choose; Tarandaly users then browse, filter, create, edit and delete those records in their own workspaces, also while offline, and your application stays the only place where data is validated, authorized and saved.

The package implements the Tarandaly Data API v1 (an open OpenAPI 3.1 protocol) at the Sync conformance level, with batches and idempotency keys:

  • schema discovery: the fields you publish, with their kinds, limits, options and relations;
  • lists with filters, search, sorting and cursors, on the fields you declare only;
  • reads and writes with optimistic concurrency (_version, If-Match, 412 with the current record);
  • atomic batches and exactly-once creations (Idempotency-Key);
  • a change feed with tombstones, 304 polling and no missed changes;
  • tokens with per-table abilities, hashed at rest, rate limits, HTTPS enforcement and RFC 9457 errors.

A complete example application lives in Tarandaly/laravel-data-api-example.

Requirements

  • PHP 8.2 or newer (8.3 or newer for Laravel 13)
  • Laravel 12 or 13
  • Any database Laravel supports (SQLite, MySQL, MariaDB, PostgreSQL, SQL Server)

Installation

composer require tarandaly/laravel-data-api
php artisan tarandaly:install   # publishes config/tarandaly-data-api.php
php artisan migrate             # tokens, change feed, idempotency keys

Quick start

1. Describe a model. Generate a starting resource from the model's table, then review it:

php artisan tarandaly:resource Customer
namespace App\Tarandaly;

use App\Models\Customer;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Tarandaly\DataApi\Context;
use Tarandaly\DataApi\Field;
use Tarandaly\DataApi\Resource;

final class CustomerResource extends Resource
{
    protected static string $model = Customer::class;

    protected static ?string $title = 'name';

    public function fields(): array
    {
        return [
            Field::text('name')->required()->max(120)->searchable()->sortable()->filterable(),
            Field::email('email')->unique()->searchable()->filterable(),
            Field::select('status', ['active' => 'Active', 'blocked' => 'Blocked'])->default('active')->filterable(),
            Field::decimal('balance', 2)->min(0)->sortable(),
            Field::belongsTo('country_id', CountryResource::class)->filterable(),
            Field::dateTime('created_at')->readOnly()->role('created_at'),
        ];
    }

    // Optional: the records a token can reach.
    public function scope(Builder $query, Context $context): void
    {
        $query->where('team_id', $context->tenant());
    }
}

2. Publish it in config/tarandaly-data-api.php:

'resources' => [
    App\Tarandaly\CountryResource::class,
    App\Tarandaly\CustomerResource::class,
],

3. Create a token for each computer or person:

php artisan tarandaly:token "Front desk PC" --ability="customers:*" --ability="countries:read"

The token is shown once; only its SHA-256 hash is stored.

4. Connect Tarandaly. In the desktop app: Add data → Web app (API), paste the address the command printed (https://your-app.example/tarandaly) and the token. Tarandaly tests the connection, reads the schema and creates the tables in the workspace.

Fields

Only the fields a resource lists are published, and only the fields that are not read-only can be written: the list is the allowlist of the API. The request body is never mass assigned.

Method Kind Value on the wire
Field::text() text string
Field::longText() long_text string (->format('markdown') for Markdown)
Field::integer() integer integer
Field::decimal($name, $scale) decimal string, e.g. "12.50"
Field::boolean() boolean true / false
Field::date() date "YYYY-MM-DD"
Field::dateTime() date_time RFC 3339 in UTC, e.g. "2026-12-06T10:15:00Z"
Field::time() time "HH:MM:SS"
Field::select($name, $options) select one option value
Field::multiSelect($name, $options) multi_select list of option values
Field::email(), url(), phone(), color() same string
Field::json() json any JSON value
Field::belongsTo($name, Resource::class) relation key of a record of the other resource

Options are ['value' => 'Label'], or [['value' => 'active', 'label' => 'Active', 'color' => 'green']] with a color from the Tarandaly palette (gray, red, orange, amber, yellow, lime, green, emerald, teal, cyan, sky, blue, indigo, violet, purple, fuchsia, pink, rose).

Modifiers:

Modifier Meaning
->required() A value is needed to create a record, and it cannot be emptied.
->nullable(false) null is refused (fields are nullable unless required).
->readOnly() Published, never written through the API.
->default($value) Used when a creation does not give the field.
->max(), ->min(), ->scale() Limits of text and numbers.
->unique() Checked with a unique rule on the model's table (for per-tenant uniqueness, use ->rules() with a scoped Rule::unique).
->rules(), ->createRules(), ->updateRules() Any extra Laravel validation rules.
->sortable(), ->searchable(), ->filterable() What lists may do with the field (->filterable(['eq', 'in']) to allow some operators only).
->attribute('column') The model attribute behind the field, when its name differs.
->readUsing(fn (Model $m) => ...) A computed, read-only value.
->role('created_at' | 'updated_at') Tells clients the field holds that time.
->label(), ->description() Shown in Tarandaly.

The model's key is published on its own (integer, string or UUID keys).

Who can do what

Every request goes through, in order:

  1. The token's abilities: customers:read, customers:write (create and update), customers:delete, customers:*, *:read, or *. A token that cannot read a table does not see it at all (absent from the schema, 404).
  2. The resource's actions: protected static array $actions = ['read']; makes a table read-only for every token.
  3. Policies: a token created with --user=<id> acts as that user, and the model's Laravel policy decides (viewAny, view, create, update, delete). Override authorize() in a resource for other rules.
  4. The resource's scope: scope() limits the records every request reaches: lists, reads, writes, relation checks and the change feed. A record outside the scope is "not found".
  5. Validation: kinds, limits, options, relation targets the token can see, then your own rules.

Tenants

A token created with --tenant=<id> is bound to a tenant. Use $context->tenant() in scope() and creating(), and return the record's tenant from tenant() so that the change feed never sends a tenant the changes of another:

public function scope(Builder $query, Context $context): void
{
    $query->where('team_id', $context->tenant());
}

public function tenant(Model $record): ?string
{
    return (string) $record->team_id;
}

public function creating(Model $record, array $values, Context $context): void
{
    $record->team_id = $context->tenant();   // what the server owns is never taken from the client
}

Hooks

creating(), updating() and deleting() run inside the transaction, before the record is saved or deleted. Throw a ProblemException to refuse with a message people understand:

use Tarandaly\DataApi\Http\ProblemException;

public function deleting(Model $record, Context $context): void
{
    if ($record->orders()->exists()) {
        throw ProblemException::conflict('A customer with orders cannot be deleted.');
    }
}

The change feed

Tarandaly keeps a copy of each table and follows GET /v1/changes to stay up to date. The package records a change whenever a published model is created, updated, deleted or restored through Eloquent, once the transaction commits.

Changes made without Eloquent events (mass updates, raw SQL, imports by other tools) are not seen automatically. Record them yourself:

use Tarandaly\DataApi\Facades\DataApi;

Customer::where('status', 'trial')->update(['status' => 'active']);
DataApi::recordChange('customers', $id);             // or DataApi::recordChange($customer)
DataApi::recordChange('customers', $id, 'delete');

DataApi::withoutRecording(fn () => $this->importThousandsOfRows());

Old changes are removed by php artisan tarandaly:prune, scheduled daily when the scheduler runs (see changes.retention_days). A client whose position is older must download the tables again (410).

The feed never skips a change that commits late: it holds back positions past a gap younger than changes.gap_seconds (5 seconds by default). Keep the clocks of your servers in sync.

In your own tests on MySQL or PostgreSQL, where ids taken by rolled-back test transactions are not reused, set tarandaly-data-api.changes.gap_seconds to 0 so that the feed serves changes at once.

Configuration

Every option is documented in config/tarandaly-data-api.php. The main ones:

Key Default Meaning
prefix, domain tarandaly, none The API answers under /{prefix}/v1.
resources [] The published resources.
require_https true Plain HTTP is refused except from the computer itself.
rate_limit.per_minute 120 Requests per minute and token.
pagination.default, pagination.max 100, 500 Page sizes.
batch.max_operations 100 null turns /batch off.
max_request_kb 1024 Largest request body.
require_if_match false Updates and deletions must send the version they change.
changes.retention_days 30 How long the change feed keeps changes.
idempotency.ttl_hours 24 How long creation answers are kept for their idempotency key.
middleware [] Extra middleware after authentication (tenancy, logging...).

Commands

Command Does
tarandaly:install Publishes the configuration and shows the next steps.
tarandaly:resource {model} Writes a starting resource from the model's table (hidden and secret-looking columns are left out).
tarandaly:token {name} --ability=... [--tenant=] [--user=] [--expires=days] Creates a token, shown once.
tarandaly:tokens [--all] Lists tokens.
tarandaly:token-revoke {id...} Revokes tokens at once.
tarandaly:prune [--days=] Removes old changes and expired idempotency keys.

Security

  • Tokens carry about 285 bits of randomness, start with tdk_ (so secret scanners recognize them) and are stored as SHA-256 hashes. Revoke a token as soon as a device is lost.
  • HTTPS is required except on the computer itself. Behind a proxy or a load balancer that ends TLS, configure trusted proxies so that requests count as secure.
  • Filters and sorting work only on declared fields, and every value reaches the database as a bound value.
  • Errors are RFC 9457 problems without stack traces or SQL, also in debug mode; server errors are still logged.
  • Answers carry Cache-Control: no-store. CORS is not enabled: tokens are for devices, not browsers.

Report vulnerabilities as described in SECURITY.md.

Testing

composer test      # Pest
composer analyse   # Larastan, level 8
composer lint      # Pint

Versioning

The package follows Semantic Versioning. Its major version follows the protocol's major version. Changes are listed in CHANGELOG.md.

License

Apache License 2.0. See LICENSE and NOTICE.