How to get Laravel Cookies

Learn how to make secure cookies with Laravel: a step-by-step guide with example.

Getting Laravel Cookies in PHP

Cookies are small text files stored on the client's browser and can be used to store sensitive information, like authentication tokens. Laravel makes it easy to both retrieve and set cookies in your application with the Cookie facade.

To get a cookie in Laravel, you can use the Cookie::get() method. This method takes the name of the cookie as an argument and returns its value. Here's an example:


$value = Cookie::get('name');

The Cookie::get() method will return a null value if the cookie doesn't exist. You can also pass a second argument to the method, which is the default value to return if the cookie doesn't exist. For example:


$value = Cookie::get('name', 'default value');

You can set a cookie using the Cookie::make() method. This method takes three parameters: the cookie's name, the value to store, and the time (in minutes) until the cookie will expire. Here's an example:


Cookie::make('name', 'value', 60);

This will create a cookie named 'name' with a value of 'value' that will expire in one hour (60 minutes).

The Cookie facade also provides a few other useful methods for dealing with cookies. You can use the Cookie::forever() method to create a cookie that will never expire. You can also use the Cookie::forget() method to delete a cookie. For example:


Cookie::forever('name', 'value');
Cookie::forget('name');

Laravel makes it easy to work with cookies in your application. With the Cookie facade, you can easily get, set, and delete cookies.

Answers (0)