'Laravel Fortify Logout Redirect
Hello guys is there any ways to redirect the logout function of Fortify?
<div class="nav-link" id="nav-bar-logoutbutton">
<form method="POST" action="{{ route('logout') }}">
@csrf
<button class="btn btn-secondary btn-sm" type="submit">Logout</button>
</form>
</div>
this is my blade logout
Solution 1:[1]
You can do the following:
Create a new LogoutResponse
class and implement your redirect logic into the toResponse
method:
"app/Http/Responses/LogoutResponse.php"
<?php
namespace App\Http\Responses;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Laravel\Fortify\Contracts\LogoutResponse as LogoutResponseContract;
use Symfony\Component\HttpFoundation\Response;
class LogoutResponse implements LogoutResponseContract
{
/**
* Create an HTTP response that represents the object.
*
* @param Request $request
*
* @return Response
*/
public function toResponse($request)
{
return $request->wantsJson()
? new JsonResponse('', 204)
: redirect('www.example.com');
}
}
Now you can bind the new response into the service container in the boot
method of your FortifyServiceProvider
:
"app/Providers/FortifyServiceProvider.php"
public function boot()
{
$this->app->singleton(
\Laravel\Fortify\Contracts\LogoutResponse::class,
\App\Http\Responses\LogoutResponse::class
);
}
Solution 2:[2]
Just create a new post request in your routes/web.php
Route::post('logout', [ClientController::class, 'logout'])->name('logout');
Now in your controller, create a function to handle the request, make sure to include the Auth class at the top.
use Auth;
/* Process the logout request */
public function logout(Request $request) {
Auth::logout();
return redirect('/login')->with(['msg_body' => 'You signed out!']);
}
Instead of /login
, you can redirect to anywhere.
Solution 3:[3]
To change logout redirect route in Laravel 9
Go to vendor/laravel/fortify/src/Http/Responses/LogoutResponse.php
public function toResponse($request)
{
return $request->wantsJson()
? new JsonResponse('', 204)
: redirect(Fortify::redirects('logout', 'Write_Your_Path'));
}
replace Write_Your_Path with your new path
Put on your mind that your path will merged with 'http://127.0.0.1:8000'; So if you write '/books', your path will be like that 'http://127.0.0.1:8000/books'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Remul |
Solution 2 | Vinny |
Solution 3 |