Search code examples
phplaravellaravel-8laravel-livewire

wire:click not firing method in its component


I am trying to implement Logout functionality on my Laravel app with TALL stack, I am firing logout event from my blade via Livewire wire:click but it doesn't seem to fire any method from its own component.

Loading my component in app.blade.php layout:

<li class="flex">
   @livewire('logout')
</li>

logout.blade.php

<a
    wire:click="logout"
    class="some-classes"
>
    <svg
        class="w-4 h-4 mr-3"
        aria-hidden="true"
        fill="none"
        stroke-linecap="round"
        stroke-linejoin="round"
        stroke-width="2"
        viewBox="0 0 24 24"
        stroke="currentColor"
    >
        <path d=""></path>
    </svg>
    <span>Log out</span>
</a>

Logout.php (Livewire Component)

<?php

namespace App\Http\Livewire;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;

class Logout extends Component
{
    use AuthorizesRequests;

    public function render()
    {
        return view('livewire.admin-panel.logout');
    }

    public function logout()
    {
        Auth::logout();
        $this->redirect(route('login'));
    }
}

I have tried dump inside function and it turned out that the methods are not being called. I have sigle root <a></a> in component's view, using <div> doen't make any difference either.

I used <button> in place of <a> and it didn't work either. I wonder what I could possibly be doing wrong here. If there's any other way of doing this that would be much appreciated.


Solution

  • Looks like the button was having an default behavior and needed wire:click.prevent

    in my logout.blade.php:

    <a
        wire:click.prevent="logout" // here
        class="some-classes"
    >
        <svg
            class="w-4 h-4 mr-3"
            aria-hidden="true"
            fill="none"
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            viewBox="0 0 24 24"
            stroke="currentColor"
        >
            <path d=""></path>
        </svg>
        <span>Log out</span>
    </a>