Learn Livewire Actions and Properties

Livewire give us super power for blade view and today we will learn about Livewire Properties and Actions.

If you new to livewire consider reading the livewire introduction post here.

Livewire Properties

Livewire let us define state into our livewire component using properties. A properties is just public variable in our livewire component. Properties in livewire is constant variable which mean you can not add non static value in it.

For example:

Let's create new component.

php artisan make:livewire comment-view

It will create this two file:

  • CLASS: app/Livewire/CommentView.php
  • VIEW: resources/views/livewire/comment-view.blade.php

In CommentView class we can define properties like this.

class CommentView extends Component
{
    public $comments = ["Comment1"];
    ...
}

If you add non hardcoded value to it will not work.

class CommentView extends Component
{
    public $comments = ["Comment1"];
    public $time = time(); // invalid properties

    ...
}

This component will throw an error:

Constant expression contains invalid operations.

A constant in PHP is only accept value a compile time, which mean the value is static, this is perfect for livewire properties because it allow us to set default state of a component.

But if you still wanted to change that value dynamically you can register mount hook to update the value after render.

class CommentView extends Component
{
    public $comments = ["Comment1"];
    public $time = 0; // invalid properties

    public function moun() {
        $this->time = time();
    }
}

Livewire Actions

With livewire we can call php function from view something that has been very hard to do with native blade view.

Let's go to CommentView class and define action reload action:

class CommentView extends Component
{
    public $comments = ["Comment1", "Comment2", "Comment3"];

    public function reload()
    {
        $this->comments[1] = Str::random(5);
    }

    public function render()
    {
        return view('livewire.comment-view');
    }
}

And print the comments data to the view in comment-view.blade.php.

<div>
    @foreach($comments as $comment)
    <p>{{$comment}}</p>
    @endforeach
</div>

Now to call the action we can add wire:click directive to listen on click event and perform reload action.

<div>
    @foreach($comments as $comment)
    <p>{{$comment}}</p>
    @endforeach
+    <button wire:click="reload">Reload</button>
</div>

Here is the livewire directive available you can use:

  1. wire:click
  2. wire:submit
  3. wire:model
  4. wire:loading
  5. wire:navigate
  6. wire:dirty
  7. wire:confirm
  8. wire:transition
  9. wire:init
  10. wire:poll
  11. wire:offline
  12. wire:ignore
  13. wire:stream