DEV Community

Cover image for Filament: Modify login or logout response
Syahril Zulkefli
Syahril Zulkefli

Posted on

Filament: Modify login or logout response

If you would like to modify Filament's default login and logout response, follow these steps.

Login Response

In my application, I want to make sure the user has at least one vehicle before they can use it, so I will redirect them to the form after they log in.

The first step is to create a new file, /app/Http/Responses/LoginResponse.php and add the logic to it.

<?php

namespace App\Http\Responses;

use App\Filament\App\Resources\VehicleResource;
use Filament\Http\Responses\Auth\Contracts\LoginResponse as Responsable;
use Filament\Pages\Dashboard;
use Illuminate\Http\RedirectResponse;
use Livewire\Features\SupportRedirects\Redirector;

class LoginResponse implements Responsable
{
    /**
     * Create an HTTP response that represents the object.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function toResponse($request): Redirector|RedirectResponse
    {
        if ($request->user()->vehicles()->count() <= 0) {
            return redirect()->to(VehicleResource::getUrl('create'));
        }

        return redirect()->to(Dashboard::getUrl());
    }
}
Enter fullscreen mode Exit fullscreen mode

Next, we have to register the implementation in our AppServiceProvider.

use App\Http\Responses\LoginResponse;
use Filament\Http\Responses\Auth\Contracts\LoginResponse as LoginResponseContract;

/**
 * Register any application services.
 */
public function register(): void
{
    $this->app->bind(
        LoginResponseContract::class,
        LoginResponse::class
    );
}
Enter fullscreen mode Exit fullscreen mode

Login Response

Since I have multiple panels in my application, I want to redirect the user to a specific login form when logged out.

For the logout, create a new file, /app/Http/Responses/LogoutResponse.php and add some logic to it.

<?php

namespace App\Http\Responses;

use Filament\Http\Responses\Auth\Contracts\LogoutResponse as Responsable;
use Illuminate\Http\RedirectResponse;

class LogoutResponse implements Responsable
{
    public function toResponse($request): RedirectResponse
    {
        // change this to your desired route
        return redirect()->route('filament.account.auth.login');
    }
}
Enter fullscreen mode Exit fullscreen mode

Don't forget to register the implementation in your AppServiceProvider.

use App\Http\Responses\LogoutResponse;
use Filament\Http\Responses\Auth\Contracts\LogoutResponse as LogoutResponseContract;

/**
 * Register any application services.
 */
public function register(): void
{
    ...
    ...

    $this->app->bind(
        LogoutResponseContract::class,
        LogoutResponse::class
    );
}
Enter fullscreen mode Exit fullscreen mode

That should do the trick.

Top comments (0)