Sometimes you might go for a shorter code. With these Magic Actions, you won't need methods in the Livewire component. In this lesson, let's see how we can use $set
and $toggle
Magic Actions.
Initial Component
Let's say we have a component to show some helper text when a button is clicked and hide it when it is clicked again. The Livewire component would have a boolean property with the default set to false
and a method to toggle the boolean value.
use Illuminate\Contracts\View\View; class ShowHelp extends Component{ public bool $showHelp = false; public function toggleHelp(): void { $this->showHelp = ! $this->showHelp; } public function render(): View { return view('livewire.show-help'); }}
In the Blade file, we would have a button with a wire:click="toggleHelp"
directive to call the toggleHelp
method after clicking it. And an if statement to show the helper text.
<div> <button wire:click="toggleHelp" class="px-4 py-2 bg-gray-800 rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-gray-700"> Toggle help </button> @if($showHelp) <div class="bg-green-100 text-green-800 px-4 py-2 mt-4"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </div> @endif</div>
After clicking the button, it toggles the helper text.
The $set
Magic Action
First, let's take a look at a $set
Magic Action. This method accepts two...