Digging Deeper

Artisan Commands

Generate resources from your tables, controllers, policies, actions, metrics and responses, and check perimeters, policies and relations with rest:check.

The package ships generators for each class it uses. The classes they write pass Pint with the laravel preset and Larastan at level 10: they import the classes they use and mark each overriding method with #[\Override].

CommandWrites
rest:quick-startthe resources, controllers, policies and routes of the models you choose
rest:resource PostResource --model=Postapp/Rest/Resources/PostResource.php
rest:controller PostsController --resource=PostResourceapp/Rest/Controllers/PostsController.php
rest:policy PostPolicy --model=Postapp/Policies/PostPolicy.php
rest:action ExtendSubscriptionsapp/Rest/Actions/ExtendSubscriptions.php
rest:instruction OddEvenIdapp/Rest/Instructions/OddEvenId.php
rest:metric OrdersByStatus --type=partition --group-by=statusapp/Rest/Metrics/OrdersByStatus.php
rest:response ArticleResponseapp/Rest/Responses/ArticleResponse.php
rest:base-resource, rest:base-controllerthe abstract base classes app/Rest/Resources/Resource.php and app/Rest/Controllers/Controller.php

rest:check writes nothing: it checks the application.

Every generator keeps an existing class: it prints <Type> already exists. and exits with 0. Pass --force (-f) to replace it.

Quick start

rest:quick-start asks which models to expose, then writes their resources from their tables, their controllers, a policy that allows every ability when Gate finds none, and one route per model behind the auth middleware of the guard, auth:sanctum by default. It checks the result in a new process before it reports success.

php artisan rest:quick-start
php artisan rest:quick-start --no-interaction --model=Post --model=Tag --install-api

See Quick start for every option.

Checking the application

rest:check checks the routes, policies, actions, metrics and instructions, perimeters, action row checks, relations, extensions and engine lists of your resources. Run it in CI:

php artisan rest:check
php artisan rest:check "App\Rest\Controllers\PostsController" --json
routes and policies ... 14 routes authenticated, 2 policies found
declarations ... 2 actions, 0 metrics, 1 instruction built
rows ... 1 resource with a perimeter, 1 marked #[WithoutPerimeter]
App\Rest\Resources\CountryResource ... #[WithoutPerimeter]
actions ... 1 action checks each row
relations ... 1 relation accepts detach
extensions ... none registered

Without arguments, it checks every controller that a route uses. It exits with 1 when:

  • a route of a controller has no authentication middleware, or a model has no policy;
  • no route uses a controller of the package;
  • an action or a metric of these controllers, or an instruction of a resource that the routes reach, through their relations too, throws when it is built, see Actions, metrics and instructions;
  • a resource that the routes reach, through their relations too, does not override perimeterQuery(), so every row is visible to users who pass viewAny, unless an extension provides its perimeter, see Perimeters from extensions;
  • an action on the Search or Resources target returns null from authorizeEach(), so no policy ability is checked on each row;
  • a relation accepts detach while the column that a detach sets to null does not accept null, see Relations that detach;
  • the text search of a resource declares what its search engine refuses, such as id in sortable() on Typesense, an index attribute that an extension declares with another field type or list marker than the resource, or a RestrictsQueries extension restricts a resource whose engine does not receive its restriction. Each is a rows problem, see Search engines;
  • an extension cannot be built or two extensions share a name, see Extensions, or a check of an extension reports a problem, see Extension checks;
  • a resource that serves its lists cannot run them on its engine, see Engine lists.
rows ... FAILED
⇂ App\Rest\Resources\JournalResource does not override perimeterQuery(): every row is visible to users who pass viewAny. Override perimeterQuery() to limit the rows, or mark the resource with #[WithoutPerimeter] when every row is meant for these users
  • Override perimeterQuery(), or mark a resource whose rows are meant for all these users, such as countries, with #[Lomkit\Rest\Attributes\WithoutPerimeter]. A subclass inherits the attribute.
  • An action that only reads returns 'view' from authorizeEach().
  • --json prints the report as an object: routes, policies, problems, search, then declarations (actions, metrics, instructions, problems), rows (perimeter, without_perimeter, problems, restricted, extension_perimeter), actions (checked, problems), relations (detachable, skipped, problems), extensions (registered, problems, notes), extension_checks (checked, problems) and engine_lists (resources, problems, notes).
  • rest:quick-start checks the routes and the policies only.

Perimeters from extensions

rest:check names the RestrictsQueries extensions that restrict the rows of each resource:

rows ... 1 resource with a perimeter, 1 with a perimeter from extensions, 2 restricted by extensions
App\Rest\Resources\DocumentResource ... perimeter from acl
App\Rest\Resources\DocumentResource ... restricted by acl
App\Rest\Resources\InvoiceResource ... restricted by tenant
  • A resource without perimeterQuery() or #[WithoutPerimeter] is still a problem when only plain RestrictsQueries extensions restrict it, and the problem then names them: a tenant extension narrows a perimeter, it does not stand for it.
  • It passes when an extension that implements ProvidesPerimeter applies to it, and gets a perimeter from line. A resource that overrides perimeterQuery() or carries #[WithoutPerimeter] keeps its report.
  • rest:check reads the config of the environment it runs in: a ProvidesPerimeter extension that is disabled there, or whose appliesTo() leaves the resource out, brings the problem back. Run it with the extensions of production.
  • In --json, rows.restricted lists every restricted resource with its RestrictsQueries extensions, and rows.extension_perimeter the resources that pass through ProvidesPerimeter extensions, as {resource, extensions} entries.

Actions, metrics and instructions

An action or a metric listed by its class is built only when it is used, so its declaration errors throw then, not when the routes register: a constructor parameter that the container cannot resolve, skipUnauthorized() without an ability, a built instance whose key or middleware differ from the defaults of its properties. rest:check builds every action and metric of the checked controllers, and fails for each one that throws:

declarations ... FAILED
⇂ App\Rest\Resources\TicketResource: App\Rest\Actions\CloseTickets is listed by its class, but its built instance has another route key or other middleware than its class declares. Set $uriKey, $name, $middleware and $withoutMiddleware as property defaults, or list the action as an instance
  • Each problem starts with the resource that lists the action or the metric. See Declaration checks.

An instruction listed by its class is built the first time a request reads the instructions of its resource, so its errors throw then. rest:check builds every instruction of the resources of the checked controllers and of every resource that their relations reach, since an include can read them. It fails for each instruction that throws: an entry that InvalidInstructionException refuses, a constructor parameter that the container cannot resolve, or another error of a constructor:

declarations ... FAILED
⇂ App\Rest\Resources\ProductResource::instructions() lists App\Rest\Instructions\RangeInstruction, which is abstract or cannot be instantiated. List a concrete class
  • Each problem names the resource that lists the instruction. See Declaration checks.
  • In --json, declarations.actions, declarations.metrics and declarations.instructions count the built actions, metrics and instructions, and declarations.problems holds the messages:
{"declarations": {"actions": 4, "metrics": 3, "instructions": 3, "problems": []}}

Relations that detach

A detach sets a link column to null: the foreign key of a BelongsTo in the table of the row, or the foreign key and the morph type of a HasOne, HasMany, MorphOne or MorphMany in the related table. When that column does not accept null, every such detach is a 422. rest:check reads the database schema of each relation that accepts detach, through the relations of the resources that the routes reach, and fails for each one whose link column does not accept null:

relations ... FAILED
⇂ App\Rest\Resources\TripResource accepts detach on its [country] relation, but trips.country_id does not accept null: each detach is refused with a 422. Add ->withoutOperations(MutationOperation::Detach) to the relation, or make the column nullable
  • Add ->withoutOperations(MutationOperation::Detach) to the relation, see Limiting the operations, or make the column nullable. A relation without detach is not read.
  • A relation whose table does not exist yet is listed as skipped, and does not fail the check: App\Rest\Resources\TripResource [country] ... skipped, no trips table. Run the check after the migrations.
  • A schema that cannot be read fails the check with a problem that names the table and the connection: App\Rest\Resources\TripResource [country]: the columns of the trips table cannot be read on the [remote] connection: ....
  • In --json, relations.detachable lists the other relations that accept detach, relations.skipped the skipped ones with their table, and relations.problems the messages.
This check is new in 3.1. A resource generated with 3.0 on a NOT NULL foreign key fails it until its relation withdraws detach or the column becomes nullable. See the Upgrade guide.

Extensions

The extensions section lists each extension with its name, its class and its origin, config when rest.extensions lists it, otherwise runtime. It builds each enabled one, and does not read the name of a disabled class:

extensions ... 2 extensions built, 1 disabled
Vendor\Acl\AccessControlExtension ... runtime, disabled
quota ... App\Rest\QuotaExtension, config
tenant ... Vendor\Tenancy\TenantExtension, runtime
  • It fails for a rest.extensions or rest.disabled_extensions value that is not a list, each refused entry, each pair of classes with one name and each class that cannot be built, and still lists the others.
  • It notes a disabled_extensions entry that disables nothing, a class that no package registers and the config does not list, without failing: The [rest.disabled_extensions] config lists Vendor\Acl\AccessControlExtension, but no extension of this class is registered or configured, so it disables nothing. Remove it, or list the exact class that the package registers.
  • Without extensions, the section prints extensions ... none registered.
  • In --json, extensions.registered lists {name, class, origin, disabled} entries, name being null for a disabled class, next to problems and notes.

Extension checks

An extension that implements ChecksResources adds checks for each resource that the checked controllers reach, through their relations too. Their problems fail the command:

extension checks ... FAILED
⇂ The [tenant_columns] extension Vendor\Tenancy\TenantColumnExtension reports App\Rest\Resources\TripResource: the trips table has no tenant_id column
  • The section shows when a check ran or reported a problem: extension checks ... 2 checks passed.
  • An exception that a check or its appliesTo() throws is a problem that names the extension and the resource. The other checks still run.
  • In --json, extension_checks.checked lists {extension, resource} entries, next to problems.

Engine lists

The engine lists section lists the resources that serve their lists through their search engine on request:

engine lists ... 1 resource lists through the search engine on request
App\Rest\Resources\ProductResource ... lists through the search engine on request
  • It fails for an engine profile that cannot list without text, and for a Scout engine that cannot be resolved.
  • It notes, without failing: a resource that overrides perimeterQuery() or defaultOrderBy(), which do not apply to its engine lists; an order of engine lists that can repeat or skip rows between pages, such as a Typesense resource without tieBreaker(); and the Scout null driver, on which the engine lists are empty.
  • A declaration that the engine search refuses, such as tieBreaker() on Algolia or id in sortable() on Typesense, is a problem of the rows section, for every resource searched through ScoutEngine.
  • rest:check reads the Scout driver of the environment it runs in: run it with the driver of production (SCOUT_DRIVER).
  • In --json, engine_lists holds resources, problems and notes.

Resources

php artisan rest:resource PostResource --model=Post --generate
  • Without --model, the model is guessed from the class name: PostResource gives App\Models\Post when that class exists.
  • The key field is ID::make() with the key name of the model.
  • rest:resource creates the base resource when it is missing.

Generating the fields and relations

--generate (-G) reads the table of the model and declares one field per column, in the order of the table, then one relation per relation method whose related model has a resource. Run it after the migrations.

PostResource ... 8 fields, 1 relation
Skipped: author: no resource for App\Models\User. Generate one first with php artisan rest:resource UserResource --model=User --generate, then run this command again with --force.
  • A cast gives the field type when one matches: a backed enum gives Enum, the JSON casts give Json, boolean, integer, decimal, float, date and datetime give Boolean, Integer, Number, Date and DateTime. Otherwise the column type decides.
  • The columns that the authentication flow writes are left out, with a note: remember_token (or the getRememberTokenName() of an Authenticatable model), two_factor_secret, two_factor_recovery_codes and two_factor_confirmed_at. password keeps its field. A hidden column that the model does not let fill, when the model declares $fillable or $guarded, is left out with a note too.
  • A nullable column gets nullable(). The timestamps, auto-increment and generated columns get readonly(). A hidden column gets writeOnly().
  • A string column whose length the database reports gets rules('max:<length>'). A column that is not nullable and has no default gets creationRules('required'), and a column with a unique index gets Rule::unique() on creation and, on update, Contextual::rule(fn (MutationContext $mutation) => Rule::unique(Post::class, 'slug')->ignore($mutation->key)).
  • A column with an encrypted cast gets filterable(false) and sortable(false).
  • A generated BelongsTo relation makes its foreign key readonly(), so clients set it through the relation.
  • A relation whose foreign key or morph type does not accept null gets ->withoutOperations(MutationOperation::Detach), so that rest:check passes. See Relations that detach.
  • A MorphTo relation is skipped, with a note that prints the declaration to write by hand. The note names the resources of the morph map models that point back to the relation, through a morphOne(), a morphMany() or a morphToMany() of the same morph name:
Skipped: commentable: MorphTo relations are not generated, declare it in relations() by hand with its targets, for example MorphTo::make('commentable', [PostResource::class, VideoResource::class]).
  • A many-to-many relation with withPivot() columns gets pivotFields([...]).

When the command runs interactively without --generate and the table exists, it asks Generate the fields and relations from the <table> table?. Read the generated fields before you expose the resource.

Controllers

php artisan rest:controller PostsController --resource=PostResource

Without --resource, the resource is guessed: PostsController gives App\Rest\Resources\PostResource. When nothing is found, the $resource line is left out and the command warns: set it before Rest::resource() registers the controller.

Policies

php artisan rest:policy PostPolicy --model=Post

The policy allows every ability to a signed-in user: viewAny(), view(), create(), update() and delete(), plus restore() and forceDelete() for a model that uses SoftDeletes. The user parameter has the type of the user model of the default guard.

When Gate already finds another policy for the model, the command prints The model [App\Models\Post] already has the policy [App\Policies\ContentPolicy]. and writes nothing.

Edit the generated policy before production. See Policies.

Metrics

php artisan rest:metric OrdersByStatus --type=partition --group-by=status
--typecalculate() returns
value$this->count($query), without ranges
trend$this->countByDays($query), with the ranges 7, 30 and 90 days
partition$this->count($query, '<group-by>')
progress$this->count($query, target: 100)
table$this->rows($query, '<group-by>', ['count' => TableColumn::count()])
customa ValueResult, in a class that extends Metric

--group-by is required for partition and table. With --no-interaction, a metric without --type is a value metric. The command prints the line to list in the resource: List it in the metrics() of a resource by its class: OrdersByStatus::class. See Metrics.

Actions, instructions and responses

  • rest:action writes an action with handle(ActionFields $fields, Collection $models) and a fields() method that returns []. It has the Search target. The command prints the line to list in the resource: List it in the actions() of a resource by its class: ExtendSubscriptions::class. See Actions.
  • rest:instruction writes an instruction with handle(InstructionFields $fields, Builder $query) and a fields() method that returns []. The command prints the line to list in the resource: List it in the instructions() of a resource by its class: OddEvenId::class. See Scopes and instructions.
  • rest:response writes a response with its map() method. See Custom responses.

Published stubs

The generators read the stubs that php artisan stub:publish copies to stubs/rest.<name>.stub, and fall back to the package stubs. A published stub keeps the placeholders that the generator fills, such as {{ namespace }} and {{ class }}. A missing placeholder throws Lomkit\Rest\Exceptions\InvalidStubException, which names the stub and the placeholder.

rest:metric reads one stub per type: rest.metric-value.stub, rest.metric-trend.stub, rest.metric-partition.stub, rest.metric-progress.stub, rest.metric-table.stub, and rest.metric.stub for custom.