Laravel 10 Fortify disable automatic login in after registration
Fortify seems to automatically log in a user after registration, which is something I want to disable.
I've seen some answers on how to do this (some on this forum), but they're all on older versions of Laravel and their solutions don't seem to work on Laravel 10 (they're about controllers that don't exist on my setup).
How can I disable this default behaviour?
I tried making changes to the CreateNewUser class, but they don't seem to work.
@stijndh Do this in your RegisterResponse in your Fortify actions
public function toResponse($request)
{
$this->guard->logout(); // logs out the session
session()->flash('success', 'We sent a verification code to you. Please verify your email to access your account.');
return $request->wantsJson()
? new JsonResponse('', 201)
: redirect()->route('login');
}
Then in your FortifyServiceProvider, add this
// Prevent Laravel auto login
app()->singleton(
\Laravel\Fortify\Contracts\RegisterResponse::class,
\App\Actions\Fortify\RegisterResponse::class,
);
Based on your answer and some more research I was able to make it work.
I added RegisterResponse.php in app/Http/Responses (I made a change to the logout code, because I got an error saying Guard didn't exist in RegisterResponse
use Illuminate\Support\Facades\Auth;
public function toResponse($request)
{
Auth::guard('web')->logout();
session()->flash('status', 'message');
return $request->wantsJson()
? new JsonResponse('', 201)
: redirect()->route('login');
}
And in my FortifyServiceProvider I added the following in the boot:
@stijndh This was my solution in laravel 11. Go to the FortifyServiceProvider class, and in the startup method, type the following.
$this->app->instance(RegisterResponse::class, new class($this->app->make(StatefulGuard::class)) implements RegisterResponse
{
private $guard;
public function __construct(StatefulGuard $guard)
{
$this->guard = $guard;
}
public function toResponse($request)
{
$this->guard->logout();
return Redirect::route('login');
}