Laravel Livewire Show and Hide Div Example

In this Laravel Livewire tutorial, we’ll explore how to hide and show a div. There are two ways to accomplish this using Livewire. First, we can create a simple method using the inequality operator (!=). Second, we can utilize Livewire’s magic actions.

Laravel Livewire Show and Hide Div

First you need to setup laravel livewire project, Then you can start below tutorial.

Create livewire component

php artisan make:livewire ShowHideComponent

Create Logic in ShowHideComponent

First you need to create public property and give relevant name. Then you need create method and pass property like this.

$this->showDiv =! $this->showDiv =! is very useful operator it pass boolean true false.

app/Http/Livewire/ShowHideComponent

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class ShowHideComponent extends Component
{
    public $showDiv = false;

    public function render()
    {
        return view('livewire.show-hide-component');
    }

    public function openDiv()
    {
        $this->showDiv =! $this->showDiv;
    }
    
}

resources/views/livewire/show-hide-component.blade.php

<div>
    <div class="container mx-auto">
        <button type="button"
            wire:click="openDiv"
            class="px-4 py-2 text-purple-100 bg-purple-500">Show & Hide Div
        </button>
        @if ($showDiv)
        <div>
            <p>Show and Hide Dive Elements in laravel livewire</p>
        </div>
        @endif
    </div>
</div>

laravel livewire show and hide dive using $toggle

$toggle(‘property’): Shortcut to toggle boolean properties on or off. $toggle is magic action that help to Livewire component re-rendering the easily.

resources/views/livewire/show-hide-component.blade.php

<div>
    <div class="container mx-auto">
        <button type="button" 
                wire:click="$toggle('showDiv')"
                class="px-4 py-2 font-bold text-purple-100 bg-purple-500">
                How & hide div
        </button>
        @if ($showDiv)
        <div class="p-4 mt-8 text-green-900 bg-green-200">
            <p>Show and Hide Dive Elements in laravel livewire</p>
        </div>
        @endif
    </div>
</div>

In shodeHideComponet you do not need create method. only just pass the public property.

app/Http/Livewire/ShowHideComponent

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class ShowHideComponent extends Component
{
    public $showDiv = false;

    public function render()
    {
        return view('livewire.show-hide-component');
    }
    
}
saim ansari
saim ansari

I'm Saim Ansari, a full-stack developer with 4+ years of hands-on experience who thrives on building web applications that leave a lasting impression. When it comes to tech, I'm particularly adept at Laravel, React, Tailwind CSS, and the Tall Stack