Multi-step form

A four-step wizard, here for creating a project: details, team, billing, then a review of every answer with a way back to each step, and a success screen at the end. Each step is a normal form post validated on the server, so it works with no script; a Livewire version follows the same view.

Multi-step form, the billing step, light and dark

Multi-step form on a phone, light and dark

A block, not a component: copy the views below into your app. It assumes the base layout. The steps use only controls that work without a script; the native select in step 2 is the input's as="select".

What it shows

  • Progress, said three ways: the stepper marks done steps and the current one (and links back to the done ones), the step heading reads "Step 3 of 4: Billing", and so does the page title.

  • Focus moves to the step heading when the reader arrives from another step, so a screen reader announces the new step and Tab carries on into its fields. The controller flashes step-moved on the redirect; the heading takes tabindex="-1" and autofocus when it is set. No script: the browser does it as the page loads. On the first step, nothing is focused.

  • Per-step validation: a step that fails comes back with each message under its field and a summary at the top that takes focus and links to each field:

    The details step with two errors, light and dark

  • Review: every answer by step, with an Edit link to that step ("Edit details" to a screen reader). Nothing is created until Create project:

    The review step, light and dark

  • Done: the stepper complete, the project named in a heading that takes focus, and where to go next:

    The project created, light and dark

Built from

  • Page header: "New project" and the way back to Projects
  • Panel: the card
  • Stepper: the four steps
  • Alert and Link: the error summary and its links
  • Input: name, key, description, the invitations, the role (a native select) and the invoice address
  • Radio: who can see it
  • Radio cards: the plan
  • Segmented control: monthly or yearly
  • Button: Back, Continue, Edit, Create project
  • Icon: the tick on the done screen

The markup

resources/views/projects/create.blade.php

{{--
    A new project in four steps, each a normal GET and POST. The controller
    passes $step (details, team, billing, review, or done once created) and
    $draft, the answers so far, kept in the session.
--}}
@php
    $steps = ['details' => 'Details', 'team' => 'Team', 'billing' => 'Billing', 'review' => 'Review'];
    $keys = array_keys($steps);
    $index = array_search($step, $keys, true);
    $position = $index === false ? count($steps) + 1 : $index + 1;
@endphp

<x-layouts.base :title="$step === 'done' ? 'Project created' : 'New project, step '.$position.' of 4: '.$steps[$step]">
    <main class="mx-auto flex max-w-3xl flex-col gap-6 px-4 py-10 sm:py-16">
        <x-ds::page-header
            title="New project"
            description="A project holds its issues, its people and its own billing."
            :backHref="route('projects.index')"
            backLabel="Projects"
        />

        <x-ds::panel body="plain">
            <x-ds::stepper label="New project progress">
                @foreach ($steps as $key => $title)
                    @php $n = $loop->iteration; @endphp
                    <x-ds::step
                        :title="$title"
                        :status="$n < $position ? 'complete' : ($n === $position ? 'current' : 'upcoming')"
                        :href="$n < $position && $step !== 'done' ? route('projects.create', $key) : null"
                    />
                @endforeach
            </x-ds::stepper>

            @if ($step === 'done')
                <div class="mt-8 flex flex-col items-start gap-4">
                    <span class="flex size-10 items-center justify-center rounded-control bg-success-tint text-on-success-tint">
                        <x-ds::icon name="check" size="5" />
                    </span>
                    {{-- Focused on arrival, so a screen reader starts at the news. --}}
                    <h2 tabindex="-1" autofocus class="text-title text-fg focus:outline-hidden">{{ $project['name'] }} is ready</h2>
                    <p class="text-body text-fg-muted">
                        We sent {{ trans_choice(':count invitation|:count invitations', $project['invited']) }}.
                        Issues in this project are numbered {{ $project['key'] }}-1, {{ $project['key'] }}-2 and so on.
                    </p>
                    <div class="flex flex-wrap gap-2">
                        <x-ds::button :href="route('projects.show', $project['key'])">Open the project</x-ds::button>
                        <x-ds::button variant="secondary" :href="route('projects.create')">Start another</x-ds::button>
                    </div>
                </div>
            @else
                @if ($errors->any())
                    {{-- Focused on arrival when a step comes back with errors. --}}
                    <x-ds::alert tone="danger" :title="$errors->count() === 1 ? 'Check one thing before you go on' : 'Check '.$errors->count().' things before you go on'" class="mt-8" tabindex="-1" autofocus>
                        <ul class="mt-1 list-disc ps-4">
                            @foreach ($errors->messages() as $field => $messages)
                                <li><x-ds::link href="#{{ $field }}" variant="danger">{{ $messages[0] }}</x-ds::link></li>
                            @endforeach
                        </ul>
                    </x-ds::alert>
                @endif

                {{--
                    Focused when the reader arrives from another step (the
                    controller flashes step-moved), so a screen reader says
                    "Step 2 of 4: Team" and Tab goes on into the step. A
                    heading is not a control, so it draws no ring.
                --}}
                <h2
                    id="step-heading"
                    tabindex="-1"
                    @if (session('step-moved') && $errors->isEmpty()) autofocus @endif
                    class="mt-8 text-title text-fg focus:outline-hidden"
                >Step {{ $position }} of 4: {{ $steps[$step] }}</h2>

                <form method="POST" action="{{ route('projects.create.store', $step) }}" class="mt-6" novalidate>
                    @csrf
                    @include('projects.steps.'.$step)

                    <div class="mt-8 flex flex-wrap justify-between gap-3 border-t border-divider pt-5">
                        @if ($index > 0)
                            <x-ds::button variant="secondary" :href="route('projects.create', $keys[$index - 1])" icon="arrow-left">Back</x-ds::button>
                        @else
                            <x-ds::button variant="ghost" :href="route('projects.index')">Cancel</x-ds::button>
                        @endif
                        <x-ds::button type="submit">{{ $step === 'review' ? 'Create project' : 'Continue' }}</x-ds::button>
                    </div>
                </form>
            @endif
        </x-ds::panel>
    </main>
</x-layouts.base>

resources/views/projects/steps/details.blade.php

<div class="flex flex-col gap-5">
    <x-ds::input
        id="name"
        name="name"
        label="Project name"
        required
        :value="old('name', $draft['name'] ?? '')"
        :error="$errors->first('name')"
    />
    <x-ds::input
        id="key"
        name="key"
        label="Key"
        help="Two to five capital letters, used in issue numbers like HBR-12."
        required
        autocapitalize="characters"
        :value="old('key', $draft['key'] ?? '')"
        :error="$errors->first('key')"
    />
    <x-ds::input
        as="textarea"
        id="description"
        name="description"
        label="Description"
        help="Optional. One or two sentences for the project list."
        :rows="3"
        :error="$errors->first('description')"
    >{{ old('description', $draft['description'] ?? '') }}</x-ds::input>
    <x-ds::radio-group label="Who can see it" :error="$errors->first('visibility')">
        @foreach (['private' => ['Only people you invite', 'Invited people and workspace admins.'], 'workspace' => ['Everyone in the workspace', 'All 24 members can find it and read its issues.']] as $value => [$label, $help])
            {{-- The first radio takes the field's id, so the error summary's link lands on it. --}}
            <x-ds::radio :id="$loop->first ? 'visibility' : 'visibility-'.$value" name="visibility" :value="$value" :label="$label" :help="$help" :checked="old('visibility', $draft['visibility'] ?? 'private') === $value" />
        @endforeach
    </x-ds::radio-group>
</div>

resources/views/projects/steps/team.blade.php

<div class="flex flex-col gap-5">
    <x-ds::input
        as="textarea"
        id="invites"
        name="invites"
        label="Invite people"
        help="Email addresses, one per line. They join when they accept."
        :rows="4"
        autocomplete="off"
        :error="$errors->first('invites')"
    >{{ old('invites', implode("\n", $draft['invites'] ?? [])) }}</x-ds::input>
    <x-ds::input as="select" id="role" name="role" label="They join as" :error="$errors->first('role')">
        @foreach (['viewer' => 'Viewer: can read and comment', 'editor' => 'Editor: can change issues', 'admin' => 'Admin: can also manage people and billing'] as $value => $label)
            <option value="{{ $value }}" @selected(old('role', $draft['role'] ?? 'editor') === $value)>{{ $label }}</option>
        @endforeach
    </x-ds::input>
</div>

resources/views/projects/steps/billing.blade.php

<div class="flex flex-col gap-6">
    <x-ds::radio-cards name="plan" label="Plan" :columns="3" :error="$errors->first('plan')">
        @foreach ([
            'starter' => ['Starter', 'Up to 5 people, 3 months of history.', '£0'],
            'team' => ['Team', 'Unlimited people and history.', '£8 a seat'],
            'business' => ['Business', 'Single sign-on and audit logs.', '£16 a seat'],
        ] as $value => [$title, $description, $price])
            <x-ds::radio-card :id="$loop->first ? 'plan' : 'plan-'.$value" :value="$value" :title="$title" :description="$description" :checked="old('plan', $draft['plan'] ?? 'team') === $value">
                <x-slot:meta>{{ $price }}</x-slot:meta>
            </x-ds::radio-card>
        @endforeach
    </x-ds::radio-cards>
    <x-ds::segmented-control name="period" label="Billed">
        <x-ds::segment value="monthly" :checked="old('period', $draft['period'] ?? 'yearly') === 'monthly'">Monthly</x-ds::segment>
        <x-ds::segment value="yearly" :checked="old('period', $draft['period'] ?? 'yearly') === 'yearly'">Yearly, two months free</x-ds::segment>
    </x-ds::segmented-control>
    <x-ds::input
        id="billing_email"
        type="email"
        name="billing_email"
        label="Send invoices to"
        autocomplete="email"
        :value="old('billing_email', $draft['billing_email'] ?? '')"
        :error="$errors->first('billing_email')"
    />
</div>

resources/views/projects/steps/review.blade.php

@php
    $plans = ['starter' => 'Starter, free', 'team' => 'Team, £8 a seat', 'business' => 'Business, £16 a seat'];
    $rows = [
        'details' => [
            'Project' => $draft['name'].' ('.$draft['key'].')',
            'Description' => $draft['description'] ?: 'None',
            'Who can see it' => $draft['visibility'] === 'workspace' ? 'Everyone in the workspace' : 'Only people you invite',
        ],
        'team' => [
            'Invitations' => $draft['invites'] ? implode(', ', $draft['invites']) : 'Nobody yet',
            'They join as' => ucfirst($draft['role']),
        ],
        'billing' => [
            'Plan' => $plans[$draft['plan']].', billed '.$draft['period'],
            'Invoices to' => $draft['billing_email'],
        ],
    ];
@endphp

<p class="text-body text-fg-muted">Nothing is created until you press Create project.</p>

<div class="mt-4 flex flex-col gap-4">
    @foreach ($rows as $section => $answers)
        <section aria-labelledby="review-{{ $section }}" class="rounded-control border border-border">
            <div class="flex items-center justify-between gap-3 border-b border-border px-4 py-2">
                <h3 id="review-{{ $section }}" class="text-section text-fg">{{ ucfirst($section) }}</h3>
                <x-ds::button variant="ghost" size="sm" :href="route('projects.create', $section)">
                    Edit<span class="sr-only"> {{ $section }}</span>
                </x-ds::button>
            </div>
            <dl class="divide-y divide-divider">
                @foreach ($answers as $label => $answer)
                    <div class="grid gap-1 px-4 py-2.5 sm:grid-cols-[10rem_1fr] sm:gap-4">
                        <dt class="text-body text-fg-muted">{{ $label }}</dt>
                        <dd class="text-body break-words text-fg">{{ $answer }}</dd>
                    </div>
                @endforeach
            </dl>
        </section>
    @endforeach
</div>

Wire it up

One controller: show draws a step from the draft in the session, store validates one step, adds it to the draft and moves on. The review posts through store as well and creates the project.

// routes/web.php
use App\Http\Controllers\NewProjectController;

Route::middleware('auth')->group(function () {
    Route::get('/projects/new/{step?}', [NewProjectController::class, 'show'])
        ->whereIn('step', ['details', 'team', 'billing', 'review', 'done'])
        ->name('projects.create');
    Route::post('/projects/new/{step}', [NewProjectController::class, 'store'])
        ->whereIn('step', ['details', 'team', 'billing', 'review'])
        ->name('projects.create.store');
});
// app/Http/Controllers/NewProjectController.php
namespace App\Http\Controllers;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class NewProjectController
{
    private const STEPS = ['details', 'team', 'billing', 'review'];

    public function show(Request $request, string $step = 'details')
    {
        if ($step === 'done') {
            $project = $request->session()->get('created') ?? abort(404);

            return view('projects.create', ['step' => 'done', 'draft' => [], 'project' => $project]);
        }

        // No skipping ahead: a step opens once every step before it is done.
        $reached = $request->session()->get('new-project.reached', 'details');
        if (array_search($step, self::STEPS) > array_search($reached, self::STEPS)) {
            return to_route('projects.create', $reached);
        }

        return view('projects.create', [
            'step' => $step,
            'draft' => $request->session()->get('new-project.draft', []),
        ]);
    }

    public function store(Request $request, string $step)
    {
        $draft = $request->session()->get('new-project.draft', []);

        if ($step === 'review') {
            // Your own: create the project and send the invitations.
            $project = $request->user()->projects()->create(collect($draft)->except('invites', 'role')->all());
            foreach ($draft['invites'] as $email) {
                $project->invite($email, $draft['role']);
            }

            $request->session()->forget('new-project');

            return to_route('projects.create', 'done')->with('created', [
                'name' => $project->name,
                'key' => $project->key,
                'invited' => count($draft['invites']),
            ]);
        }

        $answers = $request->validate($this->rules($step), [
            'key.regex' => 'Use two to five capital letters, like HBR.',
            'visibility.required' => 'Choose who can see the project.',
        ]);

        if ($step === 'team') {
            $answers['invites'] = $this->lines($answers['invites'] ?? '');
        }

        $next = self::STEPS[array_search($step, self::STEPS) + 1];
        $reached = $request->session()->get('new-project.reached', 'details');

        $request->session()->put('new-project.draft', [...$draft, ...$answers]);
        $request->session()->put('new-project.reached', array_search($next, self::STEPS) > array_search($reached, self::STEPS) ? $next : $reached);

        return to_route('projects.create', $next)->with('step-moved', true);
    }

    private function rules(string $step): array
    {
        return match ($step) {
            'details' => [
                'name' => ['required', 'string', 'max:80'],
                'key' => ['required', 'regex:/^[A-Z]{2,5}$/', Rule::unique('projects', 'key')],
                'description' => ['nullable', 'string', 'max:300'],
                'visibility' => ['required', Rule::in(['private', 'workspace'])],
            ],
            'team' => [
                'invites' => ['nullable', 'string', function (string $attribute, mixed $value, Closure $fail) {
                    foreach ($this->lines($value) as $i => $email) {
                        if (! filter_var($email, FILTER_VALIDATE_EMAIL)) {
                            $fail("{$email} is not an email address. Check line ".($i + 1).'.');
                        }
                    }
                }],
                'role' => ['required', Rule::in(['viewer', 'editor', 'admin'])],
            ],
            'billing' => [
                'plan' => ['required', Rule::in(['starter', 'team', 'business'])],
                'period' => ['required', Rule::in(['monthly', 'yearly'])],
                'billing_email' => ['required', 'email'],
            ],
        };
    }

    /** One email address per line, blank lines dropped. */
    private function lines(?string $text): array
    {
        return array_values(array_filter(array_map('trim', preg_split('/\R/', (string) $text))));
    }
}

Back is a link to the step before, so answers typed on the current step and not yet continued are not kept: say so in your help text if a step is long. Edit on the review goes to that step with its answers filled in from the draft; Continue then walks forward through the later steps, which keep theirs.

Each error message names a field, and the summary links to the element with that field's name as its id: the first radio for a radio group or radio cards, which is why those get explicit ids.

With Livewire, the step is a property and the draft is the component's own properties, so the session goes:

// app/Livewire/CreateProject.php
use Livewire\Component;

class CreateProject extends Component
{
    public string $step = 'details';
    public string $name = '';
    public string $key = '';
    // …one public property per field

    public function next(): void
    {
        $this->validate($this->rules($this->step));   // the same rules as above
        $this->step = ['details' => 'team', 'team' => 'billing', 'billing' => 'review'][$this->step];
        $this->dispatch('step-changed');
    }

    public function back(): void
    {
        $this->step = ['team' => 'details', 'billing' => 'team', 'review' => 'billing'][$this->step];
        $this->dispatch('step-changed');
    }

    public function edit(string $step): void
    {
        $this->step = $step;
        $this->dispatch('step-changed');
    }
}

In the view, the form takes wire:submit="next" in place of method and action, each field wire:model="name" and so on, Back wire:click="back" in place of its href, and each Edit wire:click="edit('team')". Focus moves on the event instead of on autofocus: give the step heading x-on:step-changed.window="$el.focus()" (no wire:key, so it is the same element after each update). The error summary and the field errors read $errors as before.

Phone, keyboard, no script

  • On a phone the stepper folds to its markers with "Step 3 of 4" and the step's title under them, the plan cards stack, and the review's labels sit above their answers.
  • Keyboard: on arriving at a step focus is on its heading; Tab goes into the fields, then Back and Continue. The radio cards and the segmented control are radio groups: one Tab stop each, arrows to choose. The stepper's done steps are links.
  • No script: everything here works. The segmented control's highlight does not slide and the radio cards are plain radios underneath; both post as they are.

From the package repo: edit this page on GitHub.

Was this page helpful?