---
title: "Server actions"
description: "Laravel classes a form or a button calls - validation, redirects, flash messages and public forms."
---

> Documentation Index
> Fetch the complete documentation index at: https://docs.rsc-kit.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Server actions

A class under `app/Rsc/Actions/` is a server action. The build writes a
`"use server"` module for it beside your pages, with one function per method,
so a client component imports it and calls it:

```php title="app/Rsc/Actions/Orders.php"
namespace App\Rsc\Actions;

use App\Http\Requests\CancelOrder;
use Illuminate\Routing\Attributes\Controllers\Middleware;
use RscKit\Rsc;

class Orders
{
#[Middleware('auth')]
public function cancel(CancelOrder $request): void
{
    $request->order()->cancel();

    Rsc::revalidate('orders');
}
}
```

```tsx title="resources/js/app/orders/CancelButton.tsx"
'use client'
import * as orders from '../../server-actions/orders'

export function CancelButton({ id }: { id: number }) {
  return <button onClick={() => orders.cancel(id)}>Cancel</button>
}
```

`Orders::cancel` is `cancel` in `server-actions/orders`. `rsc:host-manifest`
writes the class to the manifest, and the build writes the module from it.

## Making an action

```sh
php artisan make:rsc-action Orders --method=cancel --auth --can=update,Order --revalidate=orders
```

That writes the class with its guards on it and updates the manifest. A dev
server that is running starts again when the manifest changes, so the export
is there to import the moment the command returns. A class you write yourself
is picked up the next time `rsc:host-manifest` runs, which starting Vite
does.

- `--method` per call. None makes the class invokable, reached as `orders`.
- `--auth` writes `#[Middleware('auth')]`.
- `--can=ability` or `--can=ability,Model` writes `#[Authorize]`.
- `--middleware=throttle:60,1` writes `#[Middleware]`.
- `--revalidate` writes the `Rsc::revalidate()` line.
- `--form` writes a public form: see [below](#public-forms).
- A slash nests: `Billing/Invoices` is `app/Rsc/Actions/Billing/Invoices.php`,
  imported from `server-actions/billing/invoices`.

The attributes it writes are the ones the registry reads, so what you asked
for at the prompt is what runs. [Artisan commands](/hosts/laravel/commands#makersc-action)
has every option.

## Using a service

A method takes services as a controller's does, in any position. The call's
arguments are what is left, and the generated function has none for a service:

```php title="app/Rsc/Actions/Authentication.php"
use Illuminate\Container\Attributes\CurrentUser;

class Authentication
{
public function register(RegisterRequest $request, RegisterUser $register): void
{
    $register->execute($request->validated());
}

#[Middleware('auth')]
public function rename(#[CurrentUser] User $user, string $name): void
{
    $user->update(['name' => $name]);
}
}
```

```tsx
await authentication.register(form)
await authentication.rename('Ada')
```

- Guards and the form request run first. A refused form makes no service.
- `#[CurrentUser]`, `#[Config]` and Laravel's other container attributes are
  filled in by Laravel, never by the browser. A guest is answered 401 where
  `#[CurrentUser]` isn't nullable.
- A model is the page's: `Post $post` is the `{post}` of the page the form was
  posted from, bound as a route binds it. See
  [Acting on the page's record](#acting-on-the-pages-record).
- An enum, a date or a data object is never injected, and neither is a class
  that is nullable or has a default.

Needs rsc-kit/laravel 0.28.

### Taking the request

A plain `Illuminate\Http\Request` works as it does in a controller. Its input
is the form's fields, or nothing when a button calls the action, and it carries
the visitor's session, user and IP address:

```php title="app/Rsc/Actions/Authentication.php"
public function logout(Request $request): RedirectResponse
{
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();

Rsc::revalidate('all');

return to_route('home');
}
```

It is not validated. Take a `FormRequest` when the fields need rules. Use the
parameter rather than `request()`, which is the renderer's call to Laravel, not
the visitor's form.

Needs rsc-kit/laravel 0.29.

## Submitting a form

`<Form>` posts its fields to the action, and the action takes them as a form
request:

```php title="app/Http/Requests/StoreOrder.php"
class StoreOrder extends FormRequest
{
public function authorize(): bool
{
    return $this->user() !== null;
}

public function rules(): array
{
    return [
        'title' => ['required', 'string', 'max:120'],
        'quantity' => ['required', 'integer', 'min:1'],
    ];
}
}
```

```php title="app/Rsc/Actions/Orders.php"
public function store(StoreOrder $request): void
{
$request->user()->orders()->create($request->validated());

Rsc::revalidate('orders');
}
```

```tsx title="resources/js/app/orders/NewOrder.tsx"
'use client'
import { Form } from '@rsc-kit/core/form'
import * as orders from '../../server-actions/orders'

export function NewOrder() {
  return (
<Form action={orders.store}>
  {({ pending, error }) => (
    <>
      <input name="title" />
      {error('title') && <p>{error('title')}</p>}
      <input name="quantity" type="number" />
      {error('quantity') && <p>{error('quantity')}</p>}
      <button disabled={pending}>Save</button>
    </>
  )}
</Form>
  )
}
```

A failed rule shows under its field, with what was typed kept. The form works
before the page's JavaScript has loaded. [Forms](/guides/forms) covers the rest
of `<Form>`.

A form with nothing to show, such as a sign-out button, can be a plain
`<form>`, since a stub is what React's `action` takes. A redirect the action
returns is still followed:

```tsx
<form action={session.destroy}>
  <button>Sign out</button>
</form>
```

Needs `@rsc-kit/core` 0.45.3.

## Checking a field as it is filled in

A field is checked with Laravel when it is left having changed. This is
Precognition, with nothing to add: an action whose first parameter is a
`FormRequest` runs its `authorize()` and `rules()` for that field only, the
method is never called, and the message lands on `error()`.

Keep validation in the form request. Rules written inside the method can only
be checked by running it, so that action is never asked. A rule that must skip
a slow check can read `$this->isPrecognitive()`:

```php
public function rules(): array
{
return [
    'email' => ['required', 'email', ...($this->isPrecognitive() ? [] : ['unique:users'])],
];
}
```

For a wizard's step, ask at that moment with `validate()`:

```tsx
<Form action={signup.store}>
  {({ validate }) => (
<button type="button" onClick={async () => (await validate('email')) && setStep(2)}>
  Next
</button>
  )}
</Form>
```

[Forms](/guides/forms#checking-with-the-server-before-submit) has
`validating` and `valid()`.

## What the stub resolves with

The stub's type is the method's return type plus `Redirected`.

- **A redirect** resolves. A method that returns `redirect()`, `to_route()` or
  `back()`, or a guard that redirects an expired session, resolves the call with
  `{ redirected }` once the browser is on its way. Narrow with `isRedirected`
  from `@rsc-kit/core/errors` before reading a value or reporting success;
  [Redirects](/guides/redirects) has the pattern.
- **A refusal** rejects. Awaited directly, a call Laravel refuses
  (`abort(429, 'Slow down')`, `Rsc::refuse()`) rejects with an
  `ActionRefusedError` carrying the message and the status, and `<Form>` shows
  it as `formError`.
- **A `ValidationException`** rejects with a `ServerValidationError`, whose
  `.fieldErrors` and `.formErrors` are the messages.

```php
public function store(StoreOrder $request): RedirectResponse
{
$order = $request->user()->orders()->create($request->validated());

return redirect("/orders/{$order->id}");
}
```

A method answers as a controller does:

- `redirect()`, `to_route()` and `back()` are performed. `back()` is the page
  the form was posted from, and `<Form>` counts it as the save succeeding:
  `onSuccess` runs and `resetOnSuccess` resets.
- A `Responsable`, such as Fortify's `LoginResponse`, is asked what it is, and a
  `JsonResponse` is its data.
- From deeper in, throw Laravel's `HttpResponseException`. It is answered as if
  the method had returned its response.
- `back()->withErrors()` is the invalid form it says it was: a 422, each message
  under its field.
- Any other response fails loudly. A page renders the rest.

Needs rsc-kit/laravel 0.31.

An action shows an `abort()`'s message to the visitor as it is written, so give
it one: `abort(429, 'Slow down')`. Without one the form says "Refused." Only a
failure is replaced by `onError`'s generic message.

## Refreshing what the action changed

`Rsc::revalidate('orders')` says what the action made stale: an
`orders.section.tsx`, a slot, `'page'` or `'all'`. The names ride back with the
result, and the answer to the action carries the re-rendered region with it
rather than the browser being told to ask again. It is the same thing
`revalidate()` does from a JavaScript action, described in
[Sections](/guides/sections).

```php
Rsc::revalidate('orders', 'cart-count');
```

A redirect keeps the layouts as they were. When the action changed what a
layout reads (a team switch, a sign-in, a count in the sidebar), call
`Rsc::revalidate('all')` before the redirect.

For a change made outside the action, by a webhook or a job, see
[Saying data changed](/hosts/laravel/data-changed).

## A message for the next page

Flash it as on any Laravel route:

```php
return back()->with('status', 'Profile updated.');
```

The flash lasts the whole render the redirect leads to, so every read in it
finds it, and a reload does not show it again. The page reads it like any
other value of the visitor's, in its own `<Suspense>` slot:

```php title="app/Rsc/Shared.php"
public function status(): ?string
{
return session('status');
}
```

```tsx
async function Status() {
  const status = await rpc('Shared.status');

  return status ? <p role="status">{status}</p> : null;
}
```

A client component that shows it as a toast from an effect runs that effect
again when the router shows a page it kept, so remember which messages it has
shown.

Needs rsc-kit/laravel 0.31.

## Signing someone in

An action can log someone in. `Auth::login()`, or any `Cookie::queue()`, sets
the cookie on the action's answer, and the renderer puts it on the page's:

```php title="app/Rsc/Actions/Session.php"
public function store(LoginRequest $request): RedirectResponse
{
if (! Auth::attempt($request->only('email', 'password'), $request->boolean('remember'))) {
    throw ValidationException::withMessages(['email' => __('auth.failed')]);
}

$request->session()->regenerate();

Rsc::revalidate('all');

return redirect('/dashboard');
}
```

## Acting on a signed link

An action runs its guards against the page its form was posted from, so
`signed` checks the link the visitor followed:

```php title="app/Rsc/Actions/Verification.php"
use Illuminate\Foundation\Auth\EmailVerificationRequest;
use Illuminate\Routing\Attributes\Controllers\Middleware;

#[Middleware('auth')]
#[Middleware('signed')]
public function verify(EmailVerificationRequest $request): RedirectResponse
{
$request->fulfill();

return to_route('dashboard');
}
```

Posted from `/verify-email/7/3f2a…?expires=…&signature=…`, the action runs. Posted
from a link whose signature is wrong or expired, it is refused with a 403
before the method runs. The page is named `verification.verify` with
[`export const name`](/hosts/laravel/#route-names), so Laravel's own
verification email links to it.

The request the method takes carries the page's route params, so
`$request->route('id')` is the page's `{id}`, as `EmailVerificationRequest`
reads it. An argument the method names itself wins over a param of the same
name.

When the method takes a `Request`, the request its guards run against carries
the form's fields too, as the form's own post would. A limiter keyed on an
input then counts per input: Fortify's `throttle:login`, keyed on the email,
counts each email rather than one bucket for everyone. Needs rsc-kit/laravel
0.31.1.

Needs `@rsc-kit/core` 0.44 and rsc-kit/laravel 0.30.

## Acting on the page's record

Take the model as a controller does, and guard it as a route does:

```php title="app/Rsc/Actions/Posts.php"
#[Middleware('auth')]
#[Middleware('can:update,post')]
public function publish(Post $post): void
{
$post->publish();

Rsc::revalidate('page');
}
```

Posted from `/posts/1`, `$post` is post 1, bound from the page's `{post}` the
way Laravel binds a route, and it's the same post `can:update,post` was handed.
The browser never sends a model, and the stub's types leave it out. A page with
no such record answers 404, and so does a call from no page.

Binding runs where Laravel's middleware priority puts it: after `auth`, so a
guest is turned away before a record is looked up, and before `can`.

### An action guards itself

An action is a POST endpoint, and it's guarded like one. The page it says it
was posted from is chosen by whoever calls it, exactly as the `{post}` in
`POST /posts/{post}/publish` is chosen by whoever sends that request. So, as on
that route:

- Put `auth` on every action. The page's own middleware never runs for it, and
  an action can be called from any page, or from none.
- Authorize the record the action changes: `can:update,post` on the bound
  `Post $post`, or a policy check inside the method. A page param read without
  one is as trustworthy as a form field.

## Public forms

A contact form or a sign-up anyone may fill in is declared in three places: the
rules in a `FormRequest`, the action that takes it, and a few lines of
TypeScript handing that action to a form. One command writes all three:

```sh
php artisan make:rsc-action Contact --method=send --form
```

There is no schema to write: the fields and the browser's checks are read
from `rules()`.

**1. The rules.** `app/Http/Requests/SendContact.php`, which anyone may send:

```php title="app/Http/Requests/SendContact.php"
namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class SendContact extends FormRequest
{
public function authorize(): bool
{
    return true; // make:request writes false, which refuses everyone
}

public function rules(): array
{
    return [
        'name' => ['required', 'string', 'min:2'],
        'email' => ['required', 'email', 'unique:subscribers,email'],
        'topic' => ['required', 'in:sales,support'],
        'message' => ['required', 'string', 'min:10', 'max:2000'],
    ];
}
}
```

**2. The action.** Under `app/Rsc/Actions`, taking the request alone:

```php title="app/Rsc/Actions/Contact.php"
namespace App\Rsc\Actions;

use App\Http\Requests\SendContact;
use App\Models\Message;

class Contact
{
public function send(SendContact $request): void
{
    Message::create($request->validated());
}
}
```

**3. The form.** The build generates `server-actions/contact.ts` from the
class, exporting `send`, and the form is built around it. For a class you
wrote yourself, `bunx rsc-kit make:form Contact.send` writes it:

```ts title="resources/js/forms/contact.ts"
import { defineBlueprint } from '@rsc-kit/press/forms'
import { shadcn } from '@rsc-kit/press/shadcn'
import { send } from '../server-actions/contact'

export const contact = defineBlueprint({
  name: 'contact',
  actions: { create: send },
  fields: { message: { type: 'textarea' } },
  theme: shadcn,
  done: 'Thanks - we will be in touch.',
})
```

Then place it in a page, which stays static:

```tsx title="resources/js/app/contact/page.tsx"
import { contact } from '../../forms/contact'

export default function ContactPage() {
  return <contact.Form />
}
```

The fields are drawn in the order of `rules()`. `email`, `url`, `date`, `min`,
`max`, `size` and `between` become the browser's checks, and `in` or `Rule::in()`
draws a select. Everything else, `unique` included, is checked by Laravel alone:
its 422 shows under the field, with what was typed kept. A field named in
`fields` that `rules()` does not have fails the typecheck.

A rule `required_if:topic,support` shows its field only while `topic` is
`support`, and requires it then. [Blueprints](/guides/blueprints#fields-that-depend-on-others)
has the rest.

A file field, or a check in TypeScript first, needs a schema and a `handle`
instead. [Blueprints](/guides/blueprints#laravel) has the rest.

### An admin resource

An admin resource takes the same generated actions in place of a schema, and
its update takes the record's key after the request:

```php
public function update(UpdateProductRequest $request, string $product): void
```

The key is the request's route parameter under that name, so
`Rule::unique('products')->ignore($this->route('product'))` keeps the record's
own value. [The admin guide](/guides/admin/forms/#the-backends-actions-as-the-form)
has it.

### Versions

`action` taking the generated action, and `rsc-kit make:form`, need
`@rsc-kit/press` 0.30.49, and the browser's checks from `rules()` need
`rsc-kit/laravel` 0.17; an older package draws the fields with `required` and
their types only. `--form` needs `rsc-kit/laravel` 0.18. An admin update
taking the key needs `@rsc-kit/press` 0.30.51 and `rsc-kit/laravel` 0.19.
`required_if` needs `@rsc-kit/press` 0.30.52 and `rsc-kit/laravel` 0.20.

Source: https://docs.rsc-kit.dev/hosts/laravel/server-actions/index.mdx
