<x-widget.switch>
Switch
An on/off switch that submits like a checkbox and is announced as a switch. Three sizes, an optional tick and cross, before or after its text, or as a card. Works with Livewire wire:model.
php artisan larawell:add switch
- Also adds
- Icon
Usage
Livewire
In a Livewire component, bind a bool with wire:model (deferred) or wire:model.live: public bool $updates = false. No name is needed. With .live each flip reaches the server at once, so a settings page can save it in updatedUpdates() with no Save button. The switch shows the property after every render, so turning it on or off in PHP flips it.
<div class="space-y-4">
<x-widget.switch label="Email me updates" wire:model.live="updates" />
<x-widget.switch label="Dark mode" description="Follows your system until you choose." wire:model="darkMode" />
</div>
Examples
Switch
A checkbox with role="switch", so screen readers announce on and off. It submits like a checkbox.
Show code Hide code
<div class="divide-line flex max-w-md flex-col divide-y">
<x-widget.switch name="alerts" label="Withdrawal alerts" description="Email me when a withdrawal completes." checked class="py-3" />
<x-widget.switch name="two_factor" label="Two-factor authentication" class="py-3" />
<x-widget.switch name="beta" label="Beta features" disabled class="py-3" />
</div>
Switch variants
size is sm, md (default) or lg. icons puts a tick or cross in the knob, so on and off don't rely on colour alone. placement="start" puts the switch before the text, like a checkbox. variant="card" makes the whole row a tile that lights up while on.
Show code Hide code
<div class="flex flex-col gap-8">
<div class="flex flex-col gap-4">
<x-widget.switch name="compact" label="Small" size="sm" checked icons placement="start" />
<x-widget.switch name="default_size" label="Medium" checked icons placement="start" />
<x-widget.switch name="large" label="Large" size="lg" icons placement="start" />
</div>
<div class="grid gap-3 sm:grid-cols-2">
<x-widget.switch name="addons[]" value="backup" label="Daily backups" description="Kept for 30 days" variant="card" checked />
<x-widget.switch name="addons[]" value="support" label="Priority support" description="Replies within 2 hours" variant="card" />
</div>
</div>
Props
Other attributes, such as autocomplete or data-*, are passed through to the element. class styles the component's outer wrapper.
<x-widget.switch>
| Prop | Default | Description |
|---|---|---|
| name |
null
|
What it submits as; its error and old input are found under it. Optional with wire:model, which then names it. |
| id |
null
|
Defaults to one made from the name (or the wire:model property). |
| label |
null
|
Beside the switch, and its name for screen readers. |
| description |
null
|
Smaller text under the label. |
| value |
'1'
|
What it submits when on. |
| checked |
false
|
On to start with. Old input wins after a failed submit; with wire:model, the bound property. |
| unchecked-value |
null
|
Also submits this when off (e.g. 0), so the field is always in the request. |
| error |
null
|
An error message of your own; otherwise the validation error for the name, from the session or Livewire. |
| info |
null
|
A hint under the field. |
| bag |
'default'
|
Which error bag to read the error from. |
| disabled |
false
|
Greyed out: it can't be changed. |
| size |
'md'
|
sm, md or lg. |
| placement |
'end'
|
end (label first, switch after it, for settings rows) or start (switch first, like a checkbox). |
| variant |
'default'
|
default, or card: a bordered box that highlights when on. |
| icons |
false
|
A tick when on and a cross when off, so the state doesn't rest on colour alone. |
Source
What larawell:add switch writes to your app with the default namespaces. Prefer to copy by hand? Take these files, plus the ones from
the components it also adds and Field, and the theme and base CSS.
resources/views/components/widget/switch/index.blade.php Show
@props([
// What it submits as; its error and old input are found under it. Optional with wire:model, which then names it.
'name' => null,
// Defaults to one made from the name (or the wire:model property).
'id' => null,
// Beside the switch, and its name for screen readers.
'label' => null,
// Smaller text under the label.
'description' => null,
// What it submits when on.
'value' => '1',
// On to start with. Old input wins after a failed submit; with wire:model, the bound property.
'checked' => false,
// Also submits this when off (e.g. 0), so the field is always in the request.
'uncheckedValue' => null,
// An error message of your own; otherwise the validation error for the name, from the session or Livewire.
'error' => null,
// A hint under the field.
'info' => null,
// Which error bag to read the error from.
'bag' => 'default',
// Greyed out: it can't be changed.
'disabled' => false,
// sm, md or lg.
'size' => 'md',
// end (label first, switch after it, for settings rows) or start (switch first, like a checkbox).
'placement' => 'end',
// default, or card: a bordered box that highlights when on.
'variant' => 'default',
// A tick when on and a cross when off, so the state doesn't rest on colour alone.
'icons' => false,
])
@php
$field = \App\View\Widget\FormField::make($name, $id, $errors ?? null, $error, $bag, 'switch', attributes: $attributes);
// Same rule as the checkbox: after a failed submit of its own form, old input decides; otherwise `checked` does.
$isChecked = $field->checked($value, (bool) $checked, (bool) $disabled, $uncheckedValue !== null, $errors ?? null, $bag);
// Track, knob and how far the knob travels (track width - knob - 2 × 2px inset), per size. Written out in
// full so Tailwind finds every class.
$sizes = [
'sm' => ['track' => 'h-5 w-9', 'knob' => 'size-4', 'travel' => 'peer-checked:translate-x-4 rtl:peer-checked:-translate-x-4', 'icon' => 'size-2.5'],
'md' => ['track' => 'h-6 w-11', 'knob' => 'size-5', 'travel' => 'peer-checked:translate-x-5 rtl:peer-checked:-translate-x-5', 'icon' => 'size-3'],
'lg' => ['track' => 'h-7 w-13', 'knob' => 'size-6', 'travel' => 'peer-checked:translate-x-6 rtl:peer-checked:-translate-x-6', 'icon' => 'size-3.5'],
];
$size = $sizes[$size] ?? $sizes['md'];
// end: text first, switch at the end, for settings rows. start: switch first, like a checkbox.
$switchFirst = $placement === 'start';
$card = $variant === 'card';
@endphp
{{-- A checkbox with role="switch": it submits like one, and screen readers announce on / off. --}}
<x-widget.field :id="$field->id" :error="$field->errors" :info="$info" :disabled="$disabled" :required="$attributes->has('required')" bare :class="$attributes->get('class')">
@if ($uncheckedValue !== null && $name)
<input type="hidden" name="{{ $name }}" value="{{ $uncheckedValue }}">
@endif
<label for="{{ $field->id }}" @class([
'group/switch flex items-center gap-4',
'justify-between' => ! $switchFirst,
'flex-row-reverse justify-end gap-3' => $switchFirst,
// card: the whole row is a tile that lights up while on.
'border-line bg-surface rounded-2xl border p-4 transition-colors has-checked:border-primary has-checked:bg-primary/5' => $card,
'cursor-pointer' => ! $disabled,
'cursor-not-allowed opacity-60' => $disabled,
])>
<span class="min-w-0">
<span class="text-foreground">{{ $slot->isNotEmpty() ? $slot : $label }}@if ($attributes->has('required'))<span class="text-error" aria-hidden="true"> *</span>@endif</span>
@if ($description)
<span class="text-foreground/60 mt-0.5 block text-xs">{{ $description }}</span>
@endif
</span>
<span @class(['relative inline-flex shrink-0', $size['track']])>
<input
type="checkbox"
role="switch"
id="{{ $field->id }}"
@if ($name) name="{{ $name }}" @endif
value="{{ $value }}"
@checked($isChecked)
@disabled($disabled)
{{ $field->controlAttributes($attributes, (bool) $info)->class([
// muted/75: the off track, and the white knob on it, both reach 3:1; the old light grey was 1.25:1.
'peer bg-muted/75 absolute inset-0 appearance-none rounded-full transition-colors outline-none',
'checked:bg-primary focus-visible:ring-primary focus-visible:ring-2 focus-visible:ring-offset-2',
'group-data-invalid/field:ring-error group-data-invalid/field:ring-1 disabled:cursor-not-allowed',
'cursor-pointer' => ! $disabled,
]) }}
>
{{-- The knob travels toward the end edge: right, or left in RTL. --}}
<span @class([
'bg-surface pointer-events-none absolute start-0.5 top-0.5 grid place-items-center rounded-full shadow transition-transform duration-200 motion-reduce:transition-none',
$size['knob'],
$size['travel'],
])>
{{-- icons: a tick when on and a cross when off, so the state doesn't rest on colour alone. --}}
@if ($icons)
<x-widget.icon name="check" :class="'text-primary col-start-1 row-start-1 opacity-0 transition-opacity group-has-checked/switch:opacity-100 '.$size['icon']" />
<x-widget.icon name="x" :class="'text-muted col-start-1 row-start-1 transition-opacity group-has-checked/switch:opacity-0 '.$size['icon']" />
@endif
</span>
</span>
</label>
</x-widget.field>
app/View/Widget/ElementIds.php Show
<?php
declare(strict_types=1);
namespace App\View\Widget;
use Illuminate\Container\Attributes\Scoped;
use LogicException;
/**
* Keeps element ids unique within one response, so labels, aria-describedby and #fragments
* always point at the right element. Scoped: a fresh set per request (and per Octane/queue cycle).
*/
#[Scoped]
final class ElementIds
{
/** @var array<string, true> */
private array $used = [];
/**
* Reserves an id for this response.
*
* A derived id (built from a field name) gets a -2, -3 … suffix when already taken. An explicit
* id is one the caller chose and may reference from JS or CSS, so silently renaming it would
* break that reference; a duplicate throws instead, which surfaces in development and tests.
*/
public function claim(string $id, bool $explicit = false): string
{
if (!isset($this->used[$id])) {
return $this->reserve($id);
}
if ($explicit) {
throw new LogicException("Duplicate element id [{$id}] on this page. Give one of the widgets a different id or name.");
}
$suffix = 2;
while (isset($this->used["{$id}-{$suffix}"])) {
$suffix++;
}
return $this->reserve("{$id}-{$suffix}");
}
private function reserve(string $id): string
{
$this->used[$id] = true;
return $id;
}
}
app/View/Widget/FormField.php Show
<?php
declare(strict_types=1);
namespace App\View\Widget;
use Illuminate\Contracts\Support\MessageBag;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Support\ViewErrorBag;
use Illuminate\View\ComponentAttributeBag;
/**
* Server-side state of one form widget: its dot-notation key, a valid id, its validation
* messages and its old input. Every <x-widget.input.*> and the date picker resolve through
* here, so array names (items[0][date]) and named error bags behave the same everywhere.
*/
final class FormField
{
/**
* @param list<string> $errors
*/
private function __construct(
public readonly ?string $name,
public readonly string $id,
public readonly ?string $key,
public readonly array $errors,
// The property a wire:model or x-model attribute binds it to, if any.
public readonly ?string $bound = null,
) {}
/**
* @param mixed $errorBag the view's shared $errors (absent outside a web request)
* @param string|array<int, string>|null $error an explicit message from the caller; overrides the bag
*/
public static function make(
?string $name,
?string $id,
mixed $errorBag,
string|array|null $error = null,
string $bag = 'default',
string $idPrefix = 'field',
?ComponentAttributeBag $attributes = null,
): self {
// With no name, a Livewire or Alpine binding (wire:model="email") names the field. Its errors are filed under
// that property, and its id stays the same on every render, which Livewire's morph needs to keep the element
// (it matches elements by id: a random one makes it swap in a new field, dropping focus mid-typing).
$bound = $attributes === null ? null : self::boundTo($attributes);
$key = match (true) {
$name !== null && $name !== '' => self::key($name),
$bound !== null => self::key($bound),
default => null,
};
$messages = match (true) {
$error !== null => Arr::wrap($error),
$key !== null && $errorBag instanceof ViewErrorBag => self::messagesFor($errorBag->getBag($bag), $key),
default => [],
};
return new self(
$name,
app(ElementIds::class)->claim(
$id ?? ($key !== null ? self::idFrom($key) : $idPrefix.'-'.Str::random(6)),
explicit: $id !== null,
),
$key,
array_values(array_filter($messages, static fn (mixed $message): bool => is_string($message) && $message !== '')),
$bound,
);
}
/**
* The field's own messages, plus those Laravel files per item for a list of values: a 'tags.*' rule
* reports a bad second choice under tags.1, which a multiple select named tags must still show. Only
* numbered children count, so a field named address doesn't take errors meant for address[city].
*
* @return list<string>
*/
private static function messagesFor(MessageBag $bag, string $key): array
{
$items = array_filter(
$bag->getMessages(),
static fn (string $name): bool => preg_match('/^'.preg_quote($key, '/').'\.\d+$/', $name) === 1,
ARRAY_FILTER_USE_KEY,
);
return array_values(array_unique([...$bag->get($key), ...array_merge(...array_values($items))]));
}
/**
* items[0][date] → items.0.date and tags[] → tags: the key Laravel files errors and old input under.
*/
public static function key(string $name): string
{
return trim((string) preg_replace('/\[([^\]]*)\]/', '.$1', $name), '.');
}
/**
* The id a field named $name gets when it's the first of that name on the page, for links to it
* (the error summary). A later duplicate gets a -2 suffix, which links can't know about.
*/
public static function idFor(string $name): string
{
return self::idFrom(self::key($name));
}
/**
* The property a wire:model or x-model attribute (any modifiers) binds the field to; null without one.
*/
public static function boundTo(ComponentAttributeBag $attributes): ?string
{
return array_values(self::binding($attributes))[0] ?? null;
}
private static function idFrom(string $key): string
{
return trim((string) preg_replace('/[^A-Za-z0-9_-]+/', '-', $key), '-');
}
public function hasError(): bool
{
return $this->errors !== [];
}
public function errorId(): string
{
return $this->id.'-error';
}
public function infoId(): string
{
return $this->id.'-info';
}
/**
* Old input after a failed validation, falling back to the widget's value prop, or with none, to the bound Livewire
* property: a re-render then draws the field as it is, which Livewire morphs onto the page.
*/
public function old(mixed $default = null): mixed
{
if ($default === null) {
[$found, $live] = $this->fromLivewire();
$default = $found ? $live : null;
}
return $this->key === null ? $default : old($this->key, $default);
}
/**
* The bound property's value while Livewire renders the component that holds it: Livewire shares that component
* with every view as $__livewire. Livewire isn't a dependency; it's only looked for. [false, null] otherwise.
* $key reads inside it: a range bound to period reads period.start.
*
* @return array{0: bool, 1: mixed}
*/
public function fromLivewire(?string $key = null): array
{
$component = $this->bound === null ? null : view()->shared('__livewire');
return is_object($component) ? [true, data_get($component, $key === null ? $this->bound : "{$this->bound}.{$key}")] : [false, null];
}
/**
* The binding attribute as written (wire:model.live => period), to put on the inputs that carry the value: a range
* picker binds period.start and period.end with the same modifiers. Empty without one.
*
* @return array<string, string>
*/
public static function binding(ComponentAttributeBag $attributes): array
{
foreach ($attributes->getAttributes() as $attribute => $value) {
if (is_string($value) && $value !== '' && (str_starts_with($attribute, 'wire:model') || str_starts_with($attribute, 'x-model'))) {
return [$attribute => $value];
}
}
return [];
}
/**
* Whether a checkbox or switch renders ticked. An unticked box isn't in the request at all, so after a
* failed submit "no old value" means unticked, but only when that submit was this box's own form. A page
* with a second form (or a disabled box, which is never sent) would otherwise lose every `checked`.
*
* @param bool $alwaysSent it has an unchecked-value, so its form always sends something under its name
* @param mixed $errorBag the view's shared $errors
*/
public function checked(mixed $value, bool $default, bool $disabled, bool $alwaysSent, mixed $errorBag, string $bag = 'default'): bool
{
// Bound to a Livewire property: that says, true/false, or for a list of boxes, whether it holds this value.
[$found, $live] = $this->fromLivewire();
if ($found) {
return is_array($live) ? in_array(self::text($value), array_map(self::text(...), $live), true) : (bool) $live;
}
if ($this->key === null || $disabled || !session()->hasOldInput()) {
return $default;
}
$old = old($this->key);
if ($old !== null) {
return in_array(self::text($value), array_map(self::text(...), Arr::wrap($old)), true);
}
// Nothing under this name, though this box always sends something: its form wasn't the one submitted.
if ($alwaysSent) {
return $default;
}
// A form with its own error bag: no errors in that bag means the failed submit was a different form.
if ($bag !== 'default') {
return $errorBag instanceof ViewErrorBag && $errorBag->getBag($bag)->isNotEmpty() ? false : $default;
}
// One form, or forms sharing the default bag: there's no telling them apart, so trust the old input.
return false;
}
/** Values cast to backed enums (Plan::Pro) compare as their backing value. */
private static function text(mixed $value): string
{
return (string) ($value instanceof \BackedEnum ? $value->value : $value);
}
/**
* What the caller passed, minus `class` (that styles the wrapper) and the aria attributes
* this widget manages itself. Goes on the element that is actually submitted.
*/
public function forwarded(ComponentAttributeBag $attributes): ComponentAttributeBag
{
return $attributes->except(['class', 'aria-invalid', 'aria-describedby']);
}
/**
* aria-invalid plus one aria-describedby that joins the error, the hint and the caller's own
* ids. Two separate aria-describedby attributes would make the browser silently drop one.
*/
public function aria(ComponentAttributeBag $attributes, bool $hasInfo = false): ComponentAttributeBag
{
$describedBy = array_filter([
$this->hasError() ? $this->errorId() : null,
$hasInfo ? $this->infoId() : null,
$attributes->get('aria-describedby'),
]);
return new ComponentAttributeBag([
'aria-invalid' => $this->hasError() ? 'true' : null,
'aria-describedby' => $describedBy === [] ? null : implode(' ', $describedBy),
]);
}
/**
* For a widget whose visible control isn't the submitted input (grouped number, phone): what belongs on the
* hidden input that carries the value. Which form it's in, and Livewire and Alpine bindings, go with the value.
*/
public function bindings(ComponentAttributeBag $attributes): ComponentAttributeBag
{
return $attributes->filter(static fn (mixed $value, string $key): bool => self::isBinding($key));
}
/**
* The other side of bindings(): everything else the caller passed (required, autofocus, aria-label,
* placeholder…) goes on the visible control, where the browser validates it and screen readers hear it.
*/
public function visibleAttributes(ComponentAttributeBag $attributes, bool $hasInfo = false): ComponentAttributeBag
{
return $this->controlAttributes($attributes->filter(static fn (mixed $value, string $key): bool => !self::isBinding($key)), $hasInfo);
}
private static function isBinding(string $key): bool
{
return $key === 'form' || str_starts_with($key, 'wire:model') || str_starts_with($key, 'x-model');
}
/**
* forwarded() and aria() together, for widgets whose visible control is also the submitted one.
*/
public function controlAttributes(ComponentAttributeBag $attributes, bool $hasInfo = false): ComponentAttributeBag
{
return $this->forwarded($attributes)->merge($this->aria($attributes, $hasInfo)->getAttributes());
}
}