How to set and get cookie in laravel?

by jasen_gottlieb , in category: PHP Frameworks , 4 months ago

How to set and get cookie in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dedrick , 4 months ago

@jasen_gottlieb 

To set and get cookies in Laravel, you can use the Cookie facade.

  1. Setting a Cookie: To set a cookie, you can use the Cookie::queue() method. The queue() method is used to store the cookie in the response. This way, the browser will receive the cookie in the next request.


Here's an example of setting a cookie:

1
2
3
4
5
6
7
use IlluminateSupportFacadesCookie;

public function setCookie()
{
    $cookie = Cookie::queue('name', 'value', $minutes);
    return response('Cookie has been set')->withCookie($cookie);
}


In the above example, the name and value parameters represent the name and value of the cookie, and the $minutes parameter represents the duration of the cookie in minutes.

  1. Getting a Cookie: To retrieve a cookie, you can use the Cookie::get() method. This method accepts the name of the cookie as a parameter and returns its value.


Here's an example of getting a cookie:

1
2
3
4
5
6
7
use IlluminateSupportFacadesCookie;

public function getCookie(Request $request)
{
    $value = Cookie::get('name');
    return $value;
}


In the above example, name represents the name of the cookie you want to retrieve.


Note: Don't forget to import the Cookie facade at the top of your file with the use statement.