Skip to content

Mutating Actions ​

In LaravelUi5, OData is read-only. Every change to your data goes through a Ui5Action.

Reads flow through OData entity sets; every create, update, and delete flows through a named, versioned, authorization-gated action. There is no such thing as an OData write in this framework — and that is deliberate. A mutation is not a side effect of a query; it is a first-class artifact with its own identity, its own permission, its own validation contract, and its own audit surface.

An action is:

  • POST / PATCH / DELETE only — never GET or PUT,
  • reached at the api/ route prefix (distinct from the OData read surface),
  • gated by an ability you declare, enforced server-side,
  • wrapped in a database transaction the framework opens and commits (or rolls back) for you.

The shape: one command, three files ​

You never hand-write an action. Scaffold it:

bash
php artisan ui5:action Partners/CreateGroup --method=POST

That produces two files under ui5/Partners/src/Actions/, and you add a third:

FileRole
CreateGroupAction.phpThe artifact — identity, HTTP method, and the wiring to its handler and request.
Handler/CreateGroupHandler.phpThe behaviour — the state-changing logic, and nothing else.
CreateGroupRequest.phpThe contract — validates the request body and carries the authorization gate.

This separation is the whole design: the action says what it is, the request says who may call it and what a valid body looks like, and the handler changes state — reached only after identity, authorization, and validation have already passed.

1. The Action — identity + wiring ​

The action carries a stable namespace and version, its HTTP method, and pointers to its handler and request classes:

php
#[Act('createGroup', SdkRole::TenantAdmin, note: 'Create a security group definition.')]
class CreateGroupAction extends AbstractUi5Action
{
    public const string NAMESPACE = 'com.laravelui5.partners.actions.create_group';
    public const string TITLE     = 'Create Group';

    public const HttpMethod METHOD = HttpMethod::POST;
    public const string HANDLER    = CreateGroupHandler::class;
    public const string REQUEST    = CreateGroupRequest::class;
}

The #[Act] attribute is the permission (see Securing an action). The REQUEST constant names the FormRequest that validates the body; an action without a body leaves it out.

2. The Handler — sealing one outcome ​

The handler implements a single, fixed method. It reads its inputs from the request context, changes state, and seals exactly one outcome on a business transaction:

php
class UpdateGroupHandler implements SdkActionHandlerInterface
{
    public function handle(
        BusinessTransaction $transaction,
        BusinessContextInterface $context,
        SdkContext $sdk,
    ): ActionResponse {
        /** @var Group $group */
        $group = $context->parameter('group');   // a resolved route identifier
        $data  = $context->validated();           // the validated request body

        $group->update(['description' => $data['description']]);

        $transaction->touched('/Groups');         // tell the client to refresh this list
        return $transaction->commit(MessageText::of('messages.group.updated'));
    }
}

Read the three arguments as a sentence — what I seal · what I was given · who I am:

  • $transaction — the outcome you seal (below). The framework has already opened a DB transaction; your commit persists it, your rollback undoes it.
  • $context — the per-request inputs: ->validated() (the request body), ->parameter('name') (a route identifier) and ->slot('name') / ->slots() (resolved slot values).
  • $sdk — who is acting: ->actor() (the acting partner), ->abilities(), ->setting('key').

The headline you commit or rollback is a MessageText — a key in your app's bundle, resolved in the request's language before the response leaves. The messages you add ($transaction->info(...)) arrive with the resolved text beside their key and params; the client shows it.

Anything the handler needs — repositories, services — goes in its constructor; the handler is resolved from the container, so its dependencies autowire.

Sealing the transaction ​

A handler must seal exactly one outcome and return it:

CallMeaning
$transaction->commit($message = null, $data = [])Success. $message, if you give one, becomes a toast on the client; $data is the payload (e.g. a new record's id).
$transaction->rollback($message)A business failure — undoes the transaction and returns a typed error. The message is required: a refusal always says why.
$transaction->touched('/EntitySet')Marks OData paths the client should refresh after the commit.
$transaction->info(MessageText::of('messages.saved'))Attaches a business message. warning(), error() and success() attach the other severities.

Every message is a MessageText — a key in your app's bundle, resolved on the server in the user's language. There is no string variant: an exception you turn into a refusal gets a key of its own.

changed in 2.0`commit()` and `rollback()` take a `MessageText` only, and `rollback()` requires one. Before 2.0 both also took a plain string, shown as written in every language.

Returning without sealing, or returning something else, is a programming error the framework rejects. A thrown exception rolls the transaction back and returns a technical failure. You never manage the database transaction yourself — you declare the outcome, the framework commits or unwinds.

Write through models ​

A handler is a unit of work, and the audit hangs on it. Three rules follow:

  • Write only through models — create, update, delete, save, relations through a pivot model. No DB::table(...)->update(), no builder deletes, no raw SQL, no saveQuietly(). The audit sees a change only on the model.
  • Dispatch after the commit — a job, a queued listener or a mail you start goes out once your transaction committed (afterCommit()), never for a change that was rolled back.
  • No outside effects inside — an HTTP call or a file write belongs after the commit, and a handler never starts another unit of work.

3. The FormRequest — validation and the gate ​

The request extends AbstractSdkFormRequest, which supplies both the authorization check (from the action's #[Act]) and the JSON error envelope. You define the body rules:

php
class CreateGroupRequest extends AbstractSdkFormRequest
{
    public function rules(): array
    {
        return [
            'code'        => ['required', 'string', 'max:255', 'unique:sdk_groups,code'],
            'description' => ['required', 'string', 'max:2048'],
        ];
    }
}

A 422 names the fields the way your view does, if your app's bundle has the keys — fields.<field> for the name, validation.<field>.<rule> for a sentence of your own:

properties
fields.code=Group code
validation.code.unique=A group with this code exists already.

Without them Laravel's own field names and sentences apply; the sentences come from lang/. A request that overrides attributes() or messages() merges with parent::.

The request is the gate

The #[Act] ability is checked by the middleware before the controller runs (→ 403). Resolving the FormRequest then fires its own authorize() (→ 403) and validation (→ a 422) before the database transaction opens. A null request skips that second step, the FormRequest's authorization and validation, not the #[Act] gate.

Route identifiers are models, not body fields ​

An action addresses which record it acts on through a route identifier, declared with #[Parameter] on the action:

php
#[Act('updateGroup', SdkRole::TenantAdmin, note: "Edit a security group's description.")]
#[Parameter(name: 'group', uriKey: 'group', type: ParameterType::Model, model: Group::class)]
class UpdateGroupAction extends AbstractUi5Action

Route identifiers are always Eloquent models — they are route-model-bound and read in the handler via $context->parameter('group'). Everything scalar — ids in a body, flags, values — belongs in the request body, never in a #[Parameter]. This keeps the URL a stable address of objects, and the body the carrier of data.

changed in 2.0`#[Parameter]` sits on the action (Core 6.0). On the handler, the registry refuses it at boot.

Running a handler from a job or a command ​

A handler is a unit of work already: SdkActionHandlerInterface extends WorkUnitInterface, and its route parameters live on the action. So the same class can run where no request is, from a job or an audited command. Declare it as a unit of work once, beside the action:

php
final class UpdateGroupUnit extends AbstractWorkUnit
{
    public const string NAMESPACE   = 'com.acme.groups.units.update_group';
    public const string TITLE       = 'Update a group';
    public const string DESCRIPTION = 'Changes a security group\'s description.';
    public const string UNIT        = UpdateGroupHandler::class;
}

List it in the module's ARTIFACTS and run it through the runner, with the context the request would have built:

php
$runner->run($handler, new BusinessContext(['group' => $group], ['description' => 'Controls.']), $sdk);

The change log tells the two runs apart and keeps them together: namespace names the trigger, the action or the command, and unit names the declaration, from both. An action whose handler is not declared needs nothing of this; its head leaves unit empty.

Securing an action ​

Security is opt-in, and an ungated action is an open door. Declare an #[Act] on the action. The dispatcher checks it before anything else — before the body is validated, whatever the action declares — and answers 403 to an actor who does not hold it:

php
#[Act('createGroup', SdkRole::TenantAdmin, note: 'Create a security group definition.')]
  • The ability name is short and camelCase (createGroup); the action already scopes it.
  • The role is the SdkRole the ability belongs to (LocalAdmin, TenantAdmin, …).
  • The gate is inert until you run php artisan ui5:sync — the resolver reads the synced database, not live attributes. Before sync the request fails with a missing-module or missing-ability error, it is not silently open; after sync, a caller without the ability receives a 403.
  • Provide the ability's title and description in your app's bundle (abilities.act.createGroup.title / .description) — ui5:sync stops without them (Titles and descriptions). Renaming an ability is a breaking security change.
changed in 2.0The `#[Act]` check moved from the FormRequest's `authorize()` into the dispatcher. Before 2.0 an action that declared no FormRequest was not checked at all, whatever its `#[Act]` said. `authorize()` now defaults to `true`; override it for a business check of your own.

The response envelope ​

Every action resolves to one of two byte-compatible shapes, so the client has a single parse path:

jsonc
// success
{ "status": "Success", "message": "Group updated.", "data": null, "messages": [], "sideEffects": [] }

// failure: a business rollback fills messages; a validation 422 fills errors
{ "status": "Error", "message": "…", "errors": {}, "messages": [] }

The success message surfaces as a toast; sideEffects carries the touched refresh hints; messages carries business messages (resolved from i18n keys on the client).

Calling an action from the frontend ​

From a UI5 controller, call through the @laravelui5/core facade:

js
LaravelUi5.call(
  "com.laravelui5.partners.actions.update_group", // the action's NAMESPACE
  { group: id },                                  // fills the {group} route identifier
  { description }                                 // the JSON body → the FormRequest
);

The params fill the route-identifier placeholders; the body is the JSON payload (a DELETE may carry one too). An optional fourth argument, processor, names the form model that receives 422 field errors, so bound controls show their error state. The resolved response carries the commit message, the refresh hints, and any business messages. There is nothing to register on the client — each action is injected into the served manifest.json automatically, and a call to a name the manifest doesn't know throws.

At a glance ​

  • OData reads; actions write — POST / PATCH / DELETE, scaffolded with ui5:action.
  • The action declares identity + method; the request validates + gates; the handler changes state and seals one outcome.
  • Inputs come off $context (validated(), parameter()); the actor off $sdk; dependencies via the constructor.
  • The #[Act] gate fires in the middleware; the FormRequest adds its own authorization and validation.
  • Route identifiers are models; scalars go in the body.
  • Run ui5:sync to activate the security gate; call from the client with LaravelUi5.call.

See also ​