LARAVEL

Laravel Livewire Components

March 5, 2024 14 min read

Introduction

Laravel Livewire is a library that makes it simple to build modern, dynamic interfaces within Laravel, without leaving the comfort of Laravel. It allows you to write reactive, AJAX-powered interfaces while leveraging Laravel's full power.

Installation

Install Livewire via Composer:

composer require livewire/livewire

Include the scripts and styles in your layout:

@livewireStyles
<body>
    {{ $slot }}
    <script src="https://cdn.jsdelivr.net/npm/livewire/dist/livewire.js"></script>
</body>

Creating Components

Create a Livewire component:

php artisan make:livewire Counter

This creates two files:

// app/Livewire/Counter.php
namespace App\Livewire;

use Livewire\Component;

class Counter extends Component
{
    public $count = 0;

    public function render()
    {
        return view('livewire.counter');
    }
}

Properties

Define and use public properties:

class UserSearch extends Component
{
    public $search = '';
    public $users = [];
    public $perPage = 10;

    public function updatedSearch()
    {
        $this->users = User::where('name', 'like', '%' . $this->search . '%')
            ->limit($this->perPage)
            ->get();
    }

    public function render()
    {
        return view('livewire.user-search');
    }
}

Actions

Create interactive actions:

class ContactForm extends Component
{
    public $name = '';
    public $email = '';
    public $message = '';

    public function submit()
    {
        $this->validate([
            'name' => 'required|min:2',
            'email' => 'required|email',
            'message' => 'required|min:10',
        ]);

        Contact::create([
            'name' => $this->name,
            'email' => $this->email,
            'message' => $this->message,
        ]);

        session()->flash('success', 'Message sent!');

        $this->reset();
    }

    public function render()
    {
        return view('livewire.contact-form');
    }
}

Validation

Validate form data with Livewire:

protected $rules = [
    'title' => 'required|min:3',
    'content' => 'required|min:10',
    'published_at' => 'nullable|date',
];

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

    Post::create($this->all());

    session()->flash('message', 'Post created!');
}

Events

Emit and listen for events between components:

// Emit event from child component
$this->emit('postCreated', $post->id);

// Listen in parent component
protected $listeners = ['postCreated' => 'refreshPosts'];

public function refreshPosts($postId)
{
    $this->posts = Post::all();
}

Summary

Laravel Livewire provides a powerful way to build dynamic interfaces without leaving Laravel. With its reactive components, validation, and event system, Livewire makes building modern web applications fast and intuitive.

For more information, check out our other tutorials on Inertia.js and Laravel Nova.