Back to Course |
Livewire 3 From Scratch: Practical Course

Hooks: updated() and updatedField()

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.