Artisan Commands
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].
| Command | Writes |
|---|---|
rest:quick-start | the resources, controllers, policies and routes of the models you choose |
rest:resource PostResource --model=Post | app/Rest/Resources/PostResource.php |
rest:controller PostsController --resource=PostResource | app/Rest/Controllers/PostsController.php |
rest:policy PostPolicy --model=Post | app/Policies/PostPolicy.php |
rest:action ExtendSubscriptions | app/Rest/Actions/ExtendSubscriptions.php |
rest:instruction OddEvenId | app/Rest/Instructions/OddEvenId.php |
rest:metric OrdersByStatus --type=partition --group-by=status | app/Rest/Metrics/OrdersByStatus.php |
rest:response ArticleResponse | app/Rest/Responses/ArticleResponse.php |
rest:base-resource, rest:base-controller | the 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 passviewAny, unless an extension provides its perimeter, see Perimeters from extensions; - an action on the
SearchorResourcestarget returnsnullfromauthorizeEach(), so no policy ability is checked on each row; - a relation accepts
detachwhile 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
idinsortable()on Typesense, an index attribute that an extension declares with another field type or list marker than the resource, or aRestrictsQueriesextension restricts a resource whose engine does not receive its restriction. Each is arowsproblem, 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'fromauthorizeEach(). --jsonprints the report as an object:routes,policies,problems,search, thendeclarations(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) andengine_lists(resources,problems,notes).rest:quick-startchecks 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 plainRestrictsQueriesextensions 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
ProvidesPerimeterapplies to it, and gets aperimeter fromline. A resource that overridesperimeterQuery()or carries#[WithoutPerimeter]keeps its report. rest:checkreads the config of the environment it runs in: aProvidesPerimeterextension that is disabled there, or whoseappliesTo()leaves the resource out, brings the problem back. Run it with the extensions of production.- In
--json,rows.restrictedlists every restricted resource with itsRestrictsQueriesextensions, androws.extension_perimeterthe resources that pass throughProvidesPerimeterextensions, 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.metricsanddeclarations.instructionscount the built actions, metrics and instructions, anddeclarations.problemsholds 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 withoutdetachis 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.detachablelists the other relations that acceptdetach,relations.skippedthe skipped ones with theirtable, andrelations.problemsthe messages.
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.extensionsorrest.disabled_extensionsvalue 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_extensionsentry 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.registeredlists{name, class, origin, disabled}entries,namebeingnullfor a disabled class, next toproblemsandnotes.
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.checkedlists{extension, resource}entries, next toproblems.
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()ordefaultOrderBy(), 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 withouttieBreaker(); and the Scoutnulldriver, on which the engine lists are empty. - A declaration that the engine search refuses, such as
tieBreaker()on Algolia oridinsortable()on Typesense, is a problem of therowssection, for every resource searched throughScoutEngine. rest:checkreads the Scout driver of the environment it runs in: run it with the driver of production (SCOUT_DRIVER).- In
--json,engine_listsholdsresources,problemsandnotes.
Resources
php artisan rest:resource PostResource --model=Post --generate
- Without
--model, the model is guessed from the class name:PostResourcegivesApp\Models\Postwhen that class exists. - The key field is
ID::make()with the key name of the model. rest:resourcecreates 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 giveJson,boolean,integer,decimal,float,dateanddatetimegiveBoolean,Integer,Number,DateandDateTime. Otherwise the column type decides. - The columns that the authentication flow writes are left out, with a note:
remember_token(or thegetRememberTokenName()of anAuthenticatablemodel),two_factor_secret,two_factor_recovery_codesandtwo_factor_confirmed_at.passwordkeeps its field. A hidden column that the model does not let fill, when the model declares$fillableor$guarded, is left out with a note too. - A nullable column gets
nullable(). The timestamps, auto-increment and generated columns getreadonly(). A hidden column getswriteOnly(). - A string column whose length the database reports gets
rules('max:<length>'). A column that is not nullable and has no default getscreationRules('required'), and a column with a unique index getsRule::unique()on creation and, on update,Contextual::rule(fn (MutationContext $mutation) => Rule::unique(Post::class, 'slug')->ignore($mutation->key)). - A column with an
encryptedcast getsfilterable(false)andsortable(false). - A generated
BelongsTorelation makes its foreign keyreadonly(), so clients set it through the relation. - A relation whose foreign key or morph type does not accept null gets
->withoutOperations(MutationOperation::Detach), so thatrest:checkpasses. See Relations that detach. - A
MorphTorelation 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 amorphOne(), amorphMany()or amorphToMany()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 getspivotFields([...]).
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.
Metrics
php artisan rest:metric OrdersByStatus --type=partition --group-by=status
--type | calculate() 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()]) |
custom | a 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:actionwrites an action withhandle(ActionFields $fields, Collection $models)and afields()method that returns[]. It has theSearchtarget. 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:instructionwrites an instruction withhandle(InstructionFields $fields, Builder $query)and afields()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:responsewrites a response with itsmap()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.