What is Cookie in Laravel Framework?

How to Creating a Cookie

Cookie can be created by global cookie helper of Laravel. It is an instance of Symfony\Component\HttpFoundation\Cookie. The cookie can be attached to the response using the withCookie() method. Create a response instance of Illuminate\Http\Response class to call the withCookie() method. Cookie generated by the Laravel are encrypted and signed and it can’t be modified or read by the client.

File name : index.php

//Create a response instance
$response = new Response('Hello Mahi');

//Call the withCookie() method with the response method
$response->withCookie(cookie('name', 'value', $minutes));

//return the response
return $response;


Cookie() method will take 3 arguments. First argument is the name of the cookie, second argument is the value of the cookie and the third argument is the duration of the cookie after which the cookie will get deleted automatically.


Retrieving a Cookie

we can retrieve the cookie by cookie() method. This cookie() method will take only one argument which will be the name of the cookie. The cookie method can be called by using the instance of Illuminate\Http\Request.

File name : index.php

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

Example

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class CookieController extends Controller {
public function setCookie(Request $request) {
$minutes = 1;
$response = new Response('Hello World');
$response->withCookie(cookie('name', 'virat', $minutes));
return $response;
}
public function getCookie(Request $request) {
$value = $request->cookie('name');
echo $value;
}
}

Route

File name : index.php

Route::get('/cookie/set','CookieController@setCookie');
Route::get('/cookie/get','CookieController@getCookie');

Visit the following URL to set the cookie.
http://localhost:8000/cookie/set





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here


Ittutorial