Looking for a way to execute some code and, in particular delete / expire some cookies upon logging out from Laravel 8.x framework that is using Fortify and JetStream.
I noticed a couple of posts referencing the same issue, but not quite sure exactly which would be best and how to implement.
This one: Laravel Fortify Logout Redirect looks promising:
The 2nd option there says:
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
);
}
See also: Laravel Fortify
Seems like quite a bit to just do a redirect, but in my case I would actually want to expire a set of cookies and possibly do a little more housekeeping in app/Http/Responses/LogoutResponse.php.
Not exactly sure how to delete cookies in Laravel either, ? In some instances the user might not actually even be logged in and I might want to delete a cookie when they close the browser (maybe by using JS to detect closing the browser and then deleting the Cookie (HTTP only cookie on the backend ?).
$cookie = \Cookie::forget('cookie_name');