PHP: Cookies in Laravel

approximately 2 minutes of reading

In this brief tutorial I will show you the basics on how to create, return and read cookies created by Laravel. This should cover essential knowledge about cookie functionality that every developer should have when working in this fantastic framework.

Creating Cookies

As much as I love Laravel, I always put an emphasis on a fact that I don't like facades, even in terms of code aesthetics. Therefore let's inject cookie's Factory interface into a constructor. Always code to interface rather than to a concrete implementation. ☝🏻

private CookieFactory $cookieFactory;

public function __construct(
    CookieFactory $cookieFactory
) {
    $this->cookieFactory = $cookieFactory;
}

As a namespace use:

use Illuminate\Contracts\Cookie\Factory as CookieFactory;

The Factory interface has a method called make(), and this is exactly what we need. It takes 3 arguments:

  1. Name under which the cookie will be stored
  2. Value the cookie will contain
  3. Number of seconds that indicate cookie expiration

Let's create a sample cookie:

$name = 'our_cookie';
$value = 'Cookie Monster';
$minutes = 60 * 24 * 90; // 90 days in minutes

$cookie = $this->cookieFactory->make(
    $name,
    $value,
    $minutes
);

dd($cookie);

We should see a dump similar to:

Symfony\Component\HttpFoundation\Cookie {#415 ▼
  #name: "our_cookie"
  #value: "Cookie Monster"
  #domain: null
  #expire: 1674414753
  #path: "/"
  #secure: null
  #httpOnly: true
  -raw: false
  -sameSite: null
  -secureDefault: false
}
Returning Cookies

Once a cookie is created, we should include it into a response. The most typical way would be to redirect user to a specific route withCookie().

This can be done with:

return redirect()->route('frontend.index')->withCookie($cookie);

Preview your cookie in a browser of your choice.

All cookies created by Laravel are encrypted and signed with an authentication code, meaning they will be considered invalid if they have been changed by the client.
Reading Cookies

This is the most trivial part. Assuming cookie's name has not been changed since the creation (first step of this tutorial), the following code should return us the value that was stored in the cookie called our_cookie.

$name = 'our_cookie';

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

dd($result); // "Cookie Monster"

This is it. Now you know the basics about using cookies 🍪 in Laravel.


Words: 350
Published in: Laravel · PHP
Last Revision: November 09, 2022

Related Articles   📚