Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 67 ยท Livewire and the Frontend

Livewire Basics

Learn Livewire 4 in Laravel - components, properties, actions, wire:model, wire:click, validation, lifecycle hooks, pagination and single-file components.

Modern pages feel alive: a search box filters results as you type, a button adds a row without reloading, a form shows errors under the field. The usual way to build that is to write a JavaScript front end and a JSON API. Livewire takes a different route. You write the component in PHP and Blade, and Livewire keeps the browser and the server in sync for you, with no API to design and very little JavaScript.

This lesson covers Livewire 4 in a Laravel app: what a component is, how properties and actions work, how wire:model and wire:click connect the page to your class, validation, lifecycle hooks, pagination and the single-file component format. The real code is read-only, because Laravel and Livewire cannot run on this site. The runnable examples are plain-PHP stand-ins that show the idea: state lives on the server, and every interaction is a small round trip. Livewire builds on Blade components and validation, so skim those first if they are new.

How Livewire works

sequenceDiagram
    participant B as Browser
    participant L as Livewire component (PHP)
    B->>L: Page request
    L-->>B: HTML + state snapshot
    B->>L: Click: call increment() with the snapshot
    L->>L: Rebuild component, run increment()
    L-->>B: New HTML (the page updates in place)

The browser sends the component's snapshot and the action to call; the server runs your PHP and returns fresh HTML, which Livewire morphs into the page.

Two ideas matter. First, the component state lives on the server, and the browser holds a snapshot of it. Second, the browser only talks to the server when something happens (a click, a submitted form, a typed value you asked to sync), so you choose how chatty the page is.

Installing and creating a component

Livewire 4 is installed with Composer:

Terminal
composer require livewire/livewire
php artisan make:livewire counter

The starter kit with Livewire sets this up for you (authentication overview and starter kits). Livewire pages load Livewire's own JavaScript, which includes Alpine, so do not load Alpine a second time.

A component: properties and actions

In Livewire 4 the default format is a single-file component: PHP class and Blade template in one file under resources/views/components (the generator may prefix the file name with a small lightning-bolt symbol, so do not be surprised by it).

PHP
<?php

use Livewire\Component;

new class extends Component {
    public int $count = 0;

    public function increment(): void
    {
        $this->count++;
    }
};
?>

<div>
    <h2>Count: {{ $count }}</h2>
    <button wire:click="increment">Add one</button>
</div>
  • Public properties are the component's state. Livewire sends them to the browser in the snapshot, so they are visible and editable by the user. Never put secrets in them.
  • Public methods are actions. wire:click="increment" calls the method on the server and re-renders the component.
  • The Blade part can read properties directly ({{ $count }}).

Use the component anywhere in a Blade view with <livewire:counter />, or send a whole page to it from a route. Livewire 4 offers Route::livewire(...) for full-page components; check the Livewire docs for your version's exact route syntax.

If you prefer the older style, a class-based component is still supported: a PHP class in app/Livewire plus a Blade view in resources/views/livewire. The behavior is identical; only the file layout differs.

wire:model: binding inputs to properties

PHP
<?php

use Livewire\Component;

new class extends Component {
    public string $search = '';
};
?>

<div>
    <input type="text" wire:model.live.debounce.300ms="search" placeholder="Search...">
    <p>You typed: {{ $search }}</p>
</div>

wire:model binds an input to a property. How often it syncs is under your control:

Modifier Behavior
wire:model="x" Updates the server only with the next action (for example, form submit). Cheapest.
wire:model.live Sends an update on every input event.
wire:model.live.debounce.300ms Waits until the user pauses typing.
wire:model.blur Updates when the field loses focus.

Prefer the plain form and update on submit; use .live (with debounce) for search boxes and live previews, because each live update costs a request.

Forms, validation and actions

Validation works as in a controller, and errors are available with @error:

PHP
<?php

use Livewire\Attributes\Validate;
use Livewire\Component;
use App\Models\Post;

new class extends Component {
    #[Validate('required|min:3|max:100')]
    public string $title = '';

    #[Validate('required|min:20')]
    public string $body = '';

    public function save(): void
    {
        $this->validate();

        Post::create([
            'title' => $this->title,
            'body' => $this->body,
            'user_id' => auth()->id(),
        ]);

        $this->reset();
        session()->flash('status', 'Post saved.');
    }
};
?>

<form wire:submit="save">
    <input type="text" wire:model="title">
    @error('title') <span class="text-red-600">{{ $message }}</span> @enderror

    <textarea wire:model="body"></textarea>
    @error('body') <span class="text-red-600">{{ $message }}</span> @enderror

    <button type="submit">Save</button>
</form>

#[Validate] attaches rules to a property, $this->validate() checks them all and stops the action on failure, and $this->reset() returns properties to their initial values. The action runs on the server, so treat every action like a controller method: validate, and authorize with $this->authorize('update', $post) (gates and policies). A user can call any public method with any argument from the browser, and public properties can be tampered with, so never trust them blindly.

Here is a stand-in for the mechanism: a base class that takes the snapshot, applies a wire:model update, runs an action and returns the re-rendered HTML.

PHP A component stand-in: state, wire:model, actions and validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first call fails validation and re-renders with error messages; the second saves the post and returns a list. Livewire does exactly this cycle for you, except that the snapshot is encrypted and signed so the browser cannot forge component identity.

Lifecycle hooks

Livewire calls optional methods at defined moments:

Hook When it runs
mount() Once, when the component is first created. Receives parameters passed to the tag.
boot() / hydrate() On every request, when the component is rebuilt from a snapshot.
updating($name, $value) / updated($name, $value) Around any property update. Also property-specific: updatedSearch().
render() Builds the view. In single-file components the template below the PHP block is used.
dehydrate() At the end of each request, before the snapshot is sent back.
PHP
public function mount(Post $post): void       // <livewire:post-editor :post="$post" />
{
    $this->post = $post;
    $this->title = $post->title;
}

public function updatedSearch(): void         // runs after $search changes
{
    $this->resetPage();                       // go back to page 1 when filtering
}

Pass parameters through the tag with :post="$post". mount() is the right place for initial values and authorization checks.

Pagination and computed values

Add the WithPagination trait, call paginate() and show links with {{ $posts->links() }}:

PHP
<?php

use App\Models\Post;
use Livewire\Attributes\Computed;
use Livewire\Component;
use Livewire\WithPagination;

new class extends Component {
    use WithPagination;

    public string $search = '';

    public function updatedSearch(): void
    {
        $this->resetPage();
    }

    #[Computed]
    public function posts()
    {
        return Post::where('title', 'like', "%{$this->search}%")
            ->latest()
            ->paginate(10);
    }
};
?>

<div>
    <input wire:model.live.debounce.300ms="search" placeholder="Search posts">

    @foreach ($this->posts as $post)
        <article wire:key="post-{{ $post->id }}">{{ $post->title }}</article>
    @endforeach

    {{ $this->posts->links() }}
</div>

Two details to remember. A #[Computed] method is read as $this->posts and is cached for the duration of one request. And never store query results or Eloquent collections in public properties: they would be serialized into every snapshot. Use computed properties for data derived from the database. Add wire:key to items inside loops so Livewire can track them correctly.

Because Livewire pages are interactive, they usually cannot be cached for everyone the way content pages can. That is fine for apps; for public content, plain Blade pages are faster (choosing a front end).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where does a Livewire component's state live?

    The component is a PHP object on the server. The browser carries a snapshot and sends it back with each interaction so the component can be rebuilt.
  2. 2. What is the cheapest way to bind a text input to a property?

    Plain wire:model does not send a request on every keystroke. The value travels with the next action, such as the form submit.
  3. 3. Why must a public action method validate and authorize its input?

    Public methods and properties are reachable from the client. Treat each action like a controller method and check validation and policies.
  4. 4. Which hook runs once when the component is first created and receives tag parameters?

    mount() runs only on creation and is the place to set initial state from passed parameters.
  5. 5. Why use #[Computed] for a paginated query instead of a public property?

    Public properties travel to the browser and back. Keep large or sensitive data out of them and derive it in a computed property per request.

Summary

  • Livewire keeps component state on the server and updates the page with small round trips.
  • Public properties are state; public methods are actions called with wire:click or wire:submit.
  • wire:model is deferred by default; .live and .debounce make it chattier on purpose.
  • Validate with #[Validate] and $this->validate(), and authorize every action.
  • Hooks like mount() and updatedSearch() run at defined moments; use WithPagination and #[Computed] for lists.
  • Livewire 4 defaults to single-file components; class-based components still work.

Next: Blade, Livewire, Inertia or an SPA?