Laravel 8 Tutorial - Livewire Action
In this tutorial, we are going to learn about Livewire Action.
Using Livewire Action, we can listen to page interactions and also call a method on a Livewire component.
Now, let's see how we can use Livewire Action.
So, first of all, let's create a new component. For that, switch to the command prompt and create a new Livewire component by running the command:
php artisan make:livewire Action
Now, run the application:
php artisan serve
Now, switch to the project and just open the Action.php class file.
Inside this component class file, let's create a property here:
public $sum;
Now, let's create a function here:
public function addTwoNumbers($num1,$num2)
{
$this->sum = $num1+$num2;
}
Now, go to the action.blade.php view file and here create a button and call the addTwoNumbers function on click action:
<button type="button" wire:click="addTwoNumbers(22,45)">Sum</button>
{{$sum}}
Now, let's check this. So, switch to the browser and refresh the page.
Now, click on the submit button and here you can see the sum.
Now, let's see the keydown action. For that, let's add here a textarea:
<textarea></textarea>
Now, go to the Action.php class file and create a property here:
public $message;
Now, create a function here:
public function DisplayMessage($msg)
{
$this->message = $msg;
}
Now, let's call this function on keydown action. So, go to the action.blade.php view file and inside the textarea, let's add here keydown action and call the DisplayMessage function as follows:
<textarea wire:keydown.enter ="DisplayMessage($event.target.value)"><textarea>
Now, here let's display the message. So, write here after this textarea:
{{$message}}
Now, let's check this. So, switch to the browser and refresh the page.
And in textarea, let's type any text. Now, here you can see the text as we typed.
Now, let's see the submit action. For that, let's create a form here:
<form>
<input type="text" name="num1" />
<input type="text" name="num2" />
<button type="submit">Submit</button>
</form>
Now, go to the Action.php class file and here let's create a property and function:
public $num1;
public $num2;
public $sum;
public function getSum()
{
$this->sum = $this->num1 + $this->num2;
}
Now, go to the view file and bind these properties and let's call this getSum function on form submit event:
<form wire:submit.prevent="getSum">
<input type="text" name="num1" wire:model="num1" />
<input type="text" name="num2" wire:model="num2" />
<button type="submit">Submit</button>
</form>
Also, display here sum. So, write here:
{{$sum}}
Now, let's check this. So, switch to the browser and refresh the page.
Now, let's enter the first number and second number and then click on submit.
And on the page, you can see the sum of two numbers.
So, in this way, we can use Livewire Action.