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:
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');
}
}'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
php artisan make:rsc-action Orders --method=cancel --auth --can=update,Order --revalidate=ordersThat 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.
--methodper call. None makes the class invokable, reached asorders.--authwrites#[Middleware('auth')].--can=abilityor--can=ability,Modelwrites#[Authorize].--middleware=throttle:60,1writes#[Middleware].--revalidatewrites theRsc::revalidate()line.--formwrites a public form: see below.- A slash nests:
Billing/Invoicesisapp/Rsc/Actions/Billing/Invoices.php, imported fromserver-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 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:
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]);
}
}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 $postis the{post}of the page the form was posted from, bound as a route binds it. See Acting on the page’s 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:
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:
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'],
];
}
}public function store(StoreOrder $request): void
{
$request->user()->orders()->create($request->validated());
Rsc::revalidate('orders');
}'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 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:
<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():
public function rules(): array
{
return [
'email' => ['required', 'email', ...($this->isPrecognitive() ? [] : ['unique:users'])],
];
}For a wizard’s step, ask at that moment with validate():
<Form action={signup.store}>
{({ validate }) => (
<button type="button" onClick={async () => (await validate('email')) && setStep(2)}>
Next
</button>
)}
</Form>Forms 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()orback(), or a guard that redirects an expired session, resolves the call with{ redirected }once the browser is on its way. Narrow withisRedirectedfrom@rsc-kit/core/errorsbefore reading a value or reporting success; Redirects has the pattern. - A refusal rejects. Awaited directly, a call Laravel refuses
(
abort(429, 'Slow down'),Rsc::refuse()) rejects with anActionRefusedErrorcarrying the message and the status, and<Form>shows it asformError. - A
ValidationExceptionrejects with aServerValidationError, whose.fieldErrorsand.formErrorsare the messages.
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()andback()are performed.back()is the page the form was posted from, and<Form>counts it as the save succeeding:onSuccessruns andresetOnSuccessresets.- A
Responsable, such as Fortify’sLoginResponse, is asked what it is, and aJsonResponseis 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.
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.
A message for the next page
Flash it as on any Laravel route:
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:
public function status(): ?string
{
return session('status');
}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:
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:
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, 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:
#[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
authon 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,poston the boundPost $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:
php artisan make:rsc-action Contact --method=send --formThere 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:
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:
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:
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:
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
has the rest.
A file field, or a check in TypeScript first, needs a schema and a handle
instead. Blueprints 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:
public function update(UpdateProductRequest $request, string $product): voidThe 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
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.