Courses

Livewire 3 From Scratch: Practical Course

Hooks: updated() and updatedField()

Summary of this lesson:
- Using updated lifecycle hook
- Implementing dynamic property updates
- Working with dot notation properties

Livewire has a variety of lifecycle hooks that allows you to execute code at a specific time. In this lesson, let's see the updated hook.


The updated hook can be called in two ways every time the property is updated. The first way is to have an updated method that accepts two parameters, $property and $value.

Let's update the post title into a headline. Every word will have a capital first letter. In the Livewire component, we add an updated method.

use Illuminate\Support\Str;
 
class CreatePost extends Component
{
public PostForm $form;
 
// ...
 
public function updated($property): void
{
if ($property == 'form.title') {
$this->form->title = Str::headline($this->form->title);
}
}
 
// ...
}

Because we added all of the post properties to the Form Object, we can check if the updated property is correct using the dot notation. If it is the form.title, we set the title to the headline using the Laravel helper.

Now after the title is written, the title gets changed.

updated lifecycle hook

But there is a second method where doing if isn't needed. The methods syntax for that is updatedXXX where xxx is the property's name. If a property has a dot notation, like in our case, it's form.title, then it should be every word with a capital letter.

use Illuminate\Support\Str;
 
class CreatePost extends Component
{
public PostForm $form;
 
// ...
 
public function updatedFormTitle(): void
{
$this->form->title = Str::headline($this->form->title);
}
 
// ...
}

If you aren't using Form Objects and have a public property $title, then the method would be updatedTitle().

use Illuminate\Support\Str;
 
class CreatePost extends Component
{
public $title;
 
// ...
 
public function updatedTitle(): void
{
$this->title = Str::headline($this->title);
}
 
// ...
}

You can read about other lifecycle hooks in the official documentation.

Previous: Actions: wire:click and wire:keydown
avatar

Why i cant add space ? it always delete the space

👍 2
avatar

Maybe your input has .live added? Hard to say without add least some parts of the code.

avatar

If you are following the tutoral then the title input may contain the following

wire:keydown="validateTitle"

This causes the update hook to fire each time you press a key.

avatar

Or wire:model.live

avatar
You can use Markdown
avatar
You can use Markdown