What is a Cookie in Laravel?

In Laravel, a cookie is a small piece of data stored on the user’s browser, used to remember information between requests — like login status, preferences, or cart items. Laravel provides a convenient, secure way to set, get, and delete cookies.

Key Features of Laravel Cookies

  • Automatically encrypted and signed for security
  • Can be read/write across multiple requests
  • Supports expiration time, HTTP-only, and secure flags

 

Cookie Syntax Overview

1. Create / Set a Cookie

You can use the cookie() helper function:

app/Http/Controllers/CookieController.php


$cookie = cookie('name', 'John', 60); // name, value, minutes
return response('Cookie set')->cookie($cookie);

2. Read a Cookie


$name = request()->cookie('name');

3. Delete a Cookie

Set the expiration time to -1:


return response('Cookie deleted')->cookie('name', '', -1);

Laravel Cookie Example in Controller

app/Http/Controllers/CookieController.php


use Illuminate\Support\Facades\Cookie;

public function setCookie()
{
    Cookie::queue('user_id', '123', 30); // Store for 30 minutes
    return response('Cookie has been set');
}

public function getCookie()
{
    $userId = Cookie::get('user_id');
    return response("User ID from cookie: $userId");
}

Cookie Configuration File

You can manage global cookie settings in:


config/session.php

Important settings:

  • 'secure' => env('SESSION_SECURE_COOKIE', false)
  • 'http_only' => true
  • 'same_site' => 'lax'