laravel livewire show and hide div example

In this laravel livewire tutorial we see how to hide and show div. There is two ways we can show & hide div using livewire, first way we can create simple method using !=, in second way we can use livewire magic action.


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


CLASS: app/Http/Livewire/ShowHideComponent.php
VIEW: resources/views/livewire/show-hide-component.blade.php


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 (Recommended)

$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>


app/Http/Livewire/ShowHideComponent

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

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class ShowHideComponent extends Component
{
    public $showDiv = false;

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