Laravel Fortify (Jetstream) Login Without Reload Using Livewire

119 views Asked by At

I'm using Laravel Jetstream with Livewire for my authentication. I've used Livewire 3 Navigation to create links without reloading and logout without reloading. But I'm still stuck in one thing. I want to make the login itself without reloading. I tried to create my own LoginResponse and then override the original LoginResponse. But it doesn't work. When I click the "Login" button, it reloads and shows a blank page.

This is my LoginResponse, which is located in App\Livewire\LoginResponse.php:

namespace App\Livewire;

use Laravel\Fortify\Contracts\LoginResponse as ContractsLoginResponse;
use Livewire\Component;

class LoginResponse extends Component implements ContractsLoginResponse
{
    public function toResponse($request)
    {
        return $request->wantsJson()
            ? response()->json(['two_factor' => false])
            : $this->redirect('/', navigate: true);
    }
}

And then this is my code in App\Providers\FortifyServiceProvider.php:

public function boot(): void
{
    $this->app->singleton(
        \Laravel\Fortify\Contracts\LoginResponse::class,
        \App\Livewire\LoginResponse::class,
    );
}

What did I do wrong, and how can I implement the login process without reloading in Laravel Fortify (Jetstream) Livewire?

1

There are 1 answers

0
Mehdi On

One thing to consider is that Livewire only updates page elements within the scope of each Livewire component. I assume you have a login form which is a Livewire component. What you can do to update the rest of page elements, once the user logs in, is emitting a Livewire event upon successful authentication. The event can be listened to by another Livewire component and proper action can take place.

In your login function, after successful login:

public function login()
{
    // authentication logic

    // if authentication is successful
    $this->dispatch('logged-in', username: $user->name); 
}

And in another component which is responsible for some part of the page, you can list to the logged-in event:

#[On('logged-in')] 
public function updateNavBar($username)
{
    // set username value to the relevant variable and show it
}

You can read the docs on events and get a better insight on how to achieve this functionality.