Home Backend Development PHP Tutorial Laravel Livewire: What it is, and how to use it in your web app

Laravel Livewire: What it is, and how to use it in your web app

Sep 12, 2024 am 10:18 AM

Livewire is one of the most important projects in the Laravel ecosystem specifically targeted to frontend development. Livewire v3 has been recently released, so let’s explore what Livewire is, and what kind of projects fits its architecture.

The peculiarity of Livewire is that it allows the development of a "modern" web application without the need to use dedicated JavaScript frameworks.

With Livewire it is possible to develop Blade components that offer a level of reactivity equal to that offered by Vue or React, without the need to manage the complexity of a project with a decoupled frontend and backend. You can continue developing your application within the borders of Laravel and Blade templates.

How Livewire Works

Livewire is a Composer package that you can add to a Laravel project. It must then be activated on each HTML page (or the page, in case you want to create a Single Page Application) using appropriate Blade directives. Livewire components consist of a PHP class and a Blade file that contains the logic of how a specific frontend component works and it must be rendered.

When the browser asks to access a page where Livewire is used, the following happens:

  • The page is rendered with the initial states of the component, like any page created using Blade;
  • When the component UI fires an interaction an AJAX call is made to an appropriate route indicating the Livewire component and the interaction that occurred, plus the status of the component;
  • The data is processed in the PHP part of the component, which performs the new rendering as a result of the interaction and sends it back to the browser;
  • The DOM of the page is changed according to the changes received from the server.

It's very similar to what Vue and React do, but in this case the reactivity logic to respond to an interaction is managed by the backend and not in the javascript side.

To help you better understand the logic I’ll show you an example of this comparison below.

If you want to learn more about the challenges of building a developers driven company, you can follow me on Linkedin or X.

How to install Laravel Livewire

Livewire installation is absolutely minimal. Install the Composer package in your Laravel project and add the necessary Blade directives to all pages (or to the common layout from which all Blade templates in the project are derived).

composer require livewire/livewire
Copy after login
<html>
<head>
    ...

    @livewireStyles
</head>
<body>
    ...

    @livewireScripts
</body>
</html>
Copy after login

How to create a Laravel Livewire Component

Once the Composer package is installed, a new Artisan make sub-command is available to create a new Livewire component. Each component will be made with a PHP class and a Blade view.

It's similar to the class-based components of Blade.

php artisan make:livewire SpyInput    
COMPONENT CREATED ?

CLASS: app/Http/Livewire/SpyInput.php
VIEW: resources/views/livewire/spy-input.blade.php
Copy after login

The component in this example will "spy" what is written in an HTML input field, without the need to write JavaScript code.

We then insert a public property to the component class:

// app/Http/Livewire/SpyInput.php

namespace App\Livewire;

use Livewire\Component;

class SpyInput extends Component
{
    public string $message;

    public function render()
    {
        return view('livewire.spy-input');
    }
}
Copy after login

Implement the component view as follows:

// resources/views/livewire/spy-input.blade.php

<div>
    <label>Type here:</label>
    <input type="text" wire:model="message"/>
    <span>You typed: <span>{{ $message }}</span></span>
</div>
Copy after login

And finally put the Livewire component in a blade view:

<html>
<head>
    @livewireStyles
</head>
<body>

    <livewire:spy-input />

    @livewireScripts
</body>
</html>
Copy after login

In a normal Blade component all public properties of the component class are visible in the blade template. So in {{ $message }} the value of the $message property will be automatically displayed. In a normal class based component, however, this only happens on the first component rendering. If you type something in the input field nothing changes in the span tag.

In the Livewire component, however, we used the wire:model="message" attribute in the field. This attribute ensures that the value of the input field is linked to the $message property in the PHP class. When you write the new value in the input field it is sent to the server, which updates the value of $message and performs a new render, sending it back to the frontend which, then, updates the text in {{ $message }}.

By opening the Network tab of the browser's development tools, we will notice that on each key press on the keyboard makes a call to the server on the route below:

/livewire/message/<COMPONENT-NAME>
Copy after login

The response to each call contains the new rendered HTML for the component, which Livewire will insert into the page in place of the old one. Various custom wire attributes are available. For example you can execute a public method of the component class when clicking on a button. Here is an example of this biding:

<button wire:click="doSomething">Click Here</button>
Copy after login
class SpyInput extends Component
{
    public function doSomething()
    {
        // Your code here…
    }
}
Copy after login

where doSomething is a public method of the PHP class of the Livewire component.

Integration with other Laravel features

The PHP class connected to the component behaves like any other PHP class in a Laravel project. The only difference is that it uses the mount method instead of the classic __construct class constructor to initialize the public properties of the class.

{{-- Initial assignment of the the $book property in the ShowBook class --}}
<livewire:show-book :book="$book">

class ShowBook extends Component
{
    public $title;
    public $excerpt;

    // "mount" instead of "__constuct"
    public function mount(Book $book = null)
    {
        $this->title = $book->title;
        $this->excerpt = $book->excerpt;
    }
}
Copy after login

You can also use the protected property $rules to configure the validation restrictions on the data sent from the frontend to the backend. You have to call the validate() method to validate the data:

<form wire:submit.prevent="saveBook">
    <input type="text" wire:model="title"/>
    @error('title') <span class="error">{{ $message }}</span> @enderror

    <input type="text" wire:model="excerpt"/>
    @error('excerpt') <span class="error">{{ $message }}</span> @enderror

    <input type="text" wire:model="isbn"/>
    @error('isbn') <span class="error">{{ $message }}</span> @enderror

    <button type="submit">Save Book</button>
</form>
Copy after login
class BookForm extends Component
{
    public $title;
    public $excerpt;
    public $isbn;

    protected $rules = [
        'title' => ['required', 'max:200'],
        'isbn' => ['required', 'unique:books', 'size:17'],
        'excerpt' => 'max:500'
    ];

    public function saveBook()
    {
        $validated = $this->validate($this->rules);

        Book::create($validated);

        return redirect()->to('/books);
    }
}
Copy after login

Or you can use PHP Attributes to declare the desired validation rules for a class property:

class BookForm extends Component
{
    #[Validate('required|max:200')]
    public $title;

    #[Validate('required|unique:books|size:17')]
    public $isbn;

    #[Validate('max:500')]
    public $excerpt;

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

        Book::create([
            'title' => $this->title,
            'isbn' => $this->isbn,
            'excerpt' => $this->excerpt,
        ]);

        return redirect()->to('/books);
    }
}
Copy after login

In general, each Livewire component behaves in the ways that a Laravel developer expects from a PHP class inside a Laravel project. Thus allowing the creation of reactive web interfaces without the need to separate the development projects between Laravel and Vue/React.

Monitor your Laravel application for free

Inspector is a Code Execution Monitoring tool specifically designed for software developers. You don't need to install anything at the server level, just install the Laravel package and you are ready to go.

If you are looking for HTTP monitoring, database query insights, and the ability to forward alerts and notifications into your preferred messaging environment, try Inspector for free. Register your account.

Or learn more on the website: https://inspector.dev

Laravel Livewire: What it is, and how to use it in your web app

The above is the detailed content of Laravel Livewire: What it is, and how to use it in your web app. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles