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
... @livewireStyles ... @livewireScripts
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
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'); } }
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>
And finally put the Livewire component in a blade view:
@livewireStyles <spy-input></spy-input> @livewireScripts
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> </component-name>
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>
class SpyInput extends Component { public function doSomething() { // Your code here… } }
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 --}} <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; } } </show-book>
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:
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); } }
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); } }
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
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!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment