Rickin Rathatha
Rickin Rathatha

Reputation: 177

Best way to create a forever cookie when a user accesses the website in Laravel

I'm looking for the best way to create a cookie that doesn't expire when a user visits the website (the cookie holds uuid). I am using Laravel, and from what I can tell the best way seems to be using Middleware. PLease can anyone advise otherwise, and also any code examples.

Thanks

Upvotes: 0

Views: 1774

Answers (1)

user320487
user320487

Reputation:

I would use middleware for this, create a SetUserCookie middleware or similar:

class SetUserCookie { 
    public function handle($request, Closure $next) {
        $response = $next($request);
        return $response->withCookie(cookie()->forever('uuid', Str::uuid()));
    }
 }

Register the middleware in the kernel:

protected $routeMiddleware = [
    ...
    'setUserCookie' => \App\Http\Middleware\SetUserCookie::class, 
    ...
];

You can also use the queue method to attach a cookie to a response:

$minutes = 60 * 24 * 365 * 10; // ten years should be long enough
Cookie::queue(Cookie::make('uuid', Str::uuid(), $minutes));

Cookie::queue('uuid', Str::uuid(), $minutes);

Request docs

Upvotes: 3

Related Questions