Skip to content
LarawellUi

<x-widget.search>

Search

A search box that fills itself from the query string, in two sizes, with a clear button, the icon at either end and an optional keyboard shortcut. It searches as you type in a table's filters slot or with Livewire's wire:model.live; on its own it submits its form.

php artisan larawell:add search
Also adds
Icon
Used by
Phone, Select, Table

Usage

Livewire

In a Livewire component, bind with wire:model.live (add .debounce.300ms to wait for a pause in typing); no name is needed. The box shows the property after every render, so clearing it in PHP empties it too, and the × button empties the property as if the text had been deleted. Filter in render(): ->where('name', 'like', "%{$this->search}%").

Blade
<div class="space-y-4">
    <x-widget.search placeholder="Search customers" shortcut="/" wire:model.live.debounce.300ms="search" />

    <ul>
        @foreach ($customers as $customer)
            <li wire:key="{{ $customer->id }}">{{ $customer->name }}</li>
        @endforeach
    </ul>
</div>

Examples

Sizes and widths

size sets the height, matching the button and field sizes: sm (32px) beside compact controls, md (48px, the default) beside form fields. The width is the layout's: the box fills its container, so narrow it with a class such as max-w-xs. The × clears the text.

Show code
Blade
<div class="flex flex-col gap-4">
    <x-widget.search name="find" placeholder="Search transactions" />
    <x-widget.search name="find_small" placeholder="Small search" size="sm" />
    <x-widget.search name="find_narrow" placeholder="Narrow search" class="max-w-xs" />
</div>

Search form

In a GET form, Enter submits and the page reloads with ?q=…; the box fills itself back in from the query string, so the results can be shared and bookmarked. That's all it does on its own. To search as you type without a reload, put it in a table's filters slot, or bind it with wire:model.live in Livewire.

Show code
Blade
<form method="GET" role="search" class="flex max-w-md items-center gap-2">
    <x-widget.search name="q" placeholder="Search the help centre" label="Search the help centre" />
    <button type="submit" class="bg-primary text-on-primary focus-visible:ring-primary h-12 shrink-0 rounded-[20px] px-5 text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-offset-2">Search</button>
</form>

Icon at the start

icon-position="start" puts the magnifier before the text. value fills it in (the query string wins, when it has one); :clearable="false" leaves out the × button.

Show code
Blade
<div class="flex flex-col gap-4">
    <x-widget.search name="team" placeholder="Search people" icon-position="start" />
    <x-widget.search name="team_fixed" value="Design" icon-position="start" :clearable="false" size="sm" class="max-w-xs" />
</div>

Keyboard shortcut

shortcut="/" jumps to the box from anywhere on the page, as on GitHub: press / (not while typing in another field). The key shows as a hint while the box is empty and unfocused, and screen readers hear it from aria-keyshortcuts.

Show code
Blade
<x-widget.search name="docs" placeholder="Search the docs" shortcut="/" class="max-w-md" />

Props

Other attributes, such as autocomplete or data-*, are passed through to the element. class styles the component's outer wrapper.

<x-widget.search>

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).
value null Defaults to the query string under the name, so a search form fills back in; or the bound Livewire property.
placeholder 'Search' Shown while it's empty.
label null Its name for screen readers; defaults to the placeholder.
size 'md' sm (32px) or md (48px).
clearable true An × button, shown while there's text, that empties the box. It fires input and change, so whatever listens (a table's filters, wire:model) reacts as if the text had been deleted.
icon-position 'end' Where the magnifier sits: end (after the text) or start (before it).
shortcut null A key that jumps to the box from anywhere on the page, e.g. "/", shown as a hint while the box is empty and unfocused. One character, without modifiers; it doesn't fire while you're typing in another field.

Source

What larawell:add search 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/search/index.blade.php Show
index.blade.php
@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,
    // Defaults to the query string under the name, so a search form fills back in; or the bound Livewire property.
    'value' => null,
    // Shown while it's empty.
    'placeholder' => 'Search',
    // Its name for screen readers; defaults to the placeholder.
    'label' => null,
    // sm (32px) or md (48px).
    'size' => 'md',
    // An × button, shown while there's text, that empties the box. It fires input and change, so whatever listens (a
    // table's filters, wire:model) reacts as if the text had been deleted.
    'clearable' => true,
    // Where the magnifier sits: end (after the text) or start (before it).
    'iconPosition' => 'end',
    // A key that jumps to the box from anywhere on the page, e.g. "/", shown as a hint while the box is empty and
    // unfocused. One character, without modifiers; it doesn't fire while you're typing in another field.
    'shortcut' => null,
])

@php
    $field = \App\View\Widget\FormField::make($name, $id, null, idPrefix: 'search', attributes: $attributes);
    $id = $field->id;
    // Search forms submit with GET, so the current query string is the natural default (dot key: filter[q] works too).
    $fromQuery = $field->key !== null ? request()->query($field->key) : null;
    // Otherwise the value prop, or a bound Livewire property (see FormField::old).
    $value = is_string($fromQuery) ? $fromQuery : $field->old($value);
    $sizes = ['sm' => 'h-8 text-xs', 'md' => 'h-12 text-sm'];
    $size = array_key_exists($size, $sizes) ? $size : 'md';
    $start = $iconPosition === 'start';
    $shortcut = is_string($shortcut) && mb_strlen($shortcut) === 1 && trim($shortcut) !== '' ? $shortcut : null;
@endphp

<div {{ $attributes->only('class')->class([
    'bg-field text-foreground hover:border-primary focus-within:border-primary relative flex w-full items-center overflow-hidden rounded-[20px] border border-transparent transition-colors',
    $sizes[$size],
    'pe-3' => $start,
]) }}>
    @if ($start)
        <x-widget.icon name="search" class="text-muted ms-4 size-4 shrink-0" />
    @endif
    <input
        type="search"
        id="{{ $id }}"
        @if ($name) name="{{ $name }}" @endif
        value="{{ $value }}"
        {{-- A space when there's no placeholder: the clear button hides on :placeholder-shown, which needs one. --}}
        placeholder="{{ $placeholder !== '' ? $placeholder : ' ' }}"
        aria-label="{{ $label ?? $placeholder }}"
        @if ($shortcut) aria-keyshortcuts="{{ $shortcut }}" data-search-shortcut="{{ $shortcut }}" @endif
        {{ $attributes->except('class')->class([
            'peer h-full w-full min-w-0 bg-transparent outline-none placeholder:text-muted [&::-webkit-search-cancel-button]:appearance-none',
            $start ? 'ps-3' : 'ps-5',
        ]) }}
    >
    @if ($clearable)
        {{-- Hidden by CSS while the box is empty (its placeholder showing), so it needs no script to stay right, even
             when something else empties the box. The browser's own clear button is hidden above: it differs in every
             browser and Firefox has none. --}}
        <button type="button" data-search-clear aria-label="Clear search" aria-controls="{{ $id }}" @class([
            'text-muted hover:text-foreground focus-visible:ring-primary grid shrink-0 place-items-center rounded-full outline-none focus-visible:ring-2 peer-placeholder-shown:hidden',
            'me-1 size-6' => $size === 'sm',
            'me-2 size-7' => $size === 'md',
        ])>
            <x-widget.icon name="x" @class(['size-3.5' => $size === 'sm', 'size-4' => $size === 'md']) />
        </button>
    @endif
    @if ($shortcut)
        {{-- The key, until the box has focus or text; screen readers get it from aria-keyshortcuts instead. --}}
        <kbd aria-hidden="true" @class([
            'border-line-strong text-muted font-code grid shrink-0 place-items-center rounded-md border text-xs peer-focus:hidden peer-[:not(:placeholder-shown)]:hidden',
            'me-2 size-5' => $size === 'sm',
            'me-3 size-6' => $size === 'md',
        ])>{{ $shortcut }}</kbd>
    @endif
    @unless ($start)
        <x-widget.icon name="search" class="text-muted me-5 size-4 shrink-0" />
    @endunless
</div>
resources/js/widget/search/index.js Show
index.js
// Behaviour for <x-widget.search>: the clear button and the keyboard shortcut. Delegated from `document`, so fields added later work without
// re-initialising. Client-side filtering is only for convenience; the Form Request must validate the same rules.
import { on } from '../field';

// --- Search: the clear button ----------------------------------------------------------

// Empties the box and tells listeners, as deleting the text would: a table's filters refilter, wire:model updates.
// Showing and hiding the button is CSS (see search.blade.php).
on('click', '[data-search-clear]', (event, button) => {
    const input = document.getElementById(button.getAttribute('aria-controls'));
    if (!input || input.value === '') {
        return;
    }
    input.value = '';
    input.dispatchEvent(new Event('input', { bubbles: true }));
    input.dispatchEvent(new Event('change', { bubbles: true }));
    input.focus();
});

// shortcut="/": the key jumps to the box, unless you're typing somewhere else or a dialog is open over it (then only
// a box inside that dialog counts). The first visible box with that key wins.
document.addEventListener('keydown', (event) => {
    if (event.defaultPrevented || event.ctrlKey || event.metaKey || event.altKey || event.key.length !== 1) {
        return;
    }
    const target = event.target;
    if (target instanceof Element && target.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"])')) {
        return;
    }
    const dialog = document.querySelector('dialog[open]');
    const box = [...document.querySelectorAll('[data-search-shortcut]')].find((input) => input.dataset.searchShortcut.toLowerCase() === event.key.toLowerCase()
        && input.offsetParent !== null && (!dialog || dialog.contains(input)));
    if (box) {
        event.preventDefault();
        box.focus();
        box.select();
    }
});
app/View/Widget/ElementIds.php Show
ElementIds.php
<?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
FormField.php
<?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());
    }
}