A Livewire component is a self-contained unit of logic and UI. It contains both backend logic (written in PHP) and frontend rendering (done via Blade templates). With Livewire 3.0, these components are stored in the app/Livewire
f older by default, ensuring a cleaner and more intuitive directory structure.
To create a new Livewire component, run the following command in your terminal:
php artisan make:livewire HelloWorld
This will create two files:
app/Livewire/HelloWorld.php
– The PHP class that contains the logic for your component.
resources/views/livewire/hello-world.blade.php
– The Blade template for the component’s UI.
Here’s what the generated PHP class looks like:
Namespace: Components are stored in the App\Livewire
namespace.
render()
method: This method defines the Blade view that will be rendered.
Here’s the generated Blade file:
Hello, World!
This file will be displayed when the component is rendered.
To use the component, include it in any Blade template, like welcome.blade.php
:
Visit your application in the browser (e.g., http://localhost:8000
), and you’ll see:
Hello, World!
Let’s enhance the HelloWorld
component to display dynamic content.
Add a public property and a method to update it:
name = $newName;
}
public function render()
{
return view('livewire.hello-world');
}
}
Modify hello-world.blade.php
to include a text input and a button:
Hello, {{ $name }}!
wire:model
: Binds the text input to the $name
property in the PHP class. Changes to the input are reflected in real time.
wire:click
: Triggers the updateName()
method when the button is clicked.
Livewire provides hooks to manage the lifecycle of your components. Here are some key hooks:
mount()
: Called when the component is initialized.
updated($propertyName)
: Called after a property is updated.
render()
: Called to render the component’s Blade template.
Let’s add a mount()
hook to set a default value for $name
:
public function mount()
{
$this->name = 'Livewire 3.0';
}
With the above changes, visiting your page now allows users to:
See Hello, Livewire 3.0!
as the default text.
Update the name dynamically by typing into the input field.
Change the name to Laravel
by clicking the button.
410 C, Jaina Tower-1, District Center, Janak Puri New Delhi-110058, India.
© Copyright 2025 Wontonee. All Right Reserved.