In this article we will learn to set and get cookies in laravel. Cookies are used to store the data in client computer, Cookie can hold tiny information in computer and can retrieve when required for same website. In laravel we can store and fetch cookies using laravel inbuilt methods like queue
, response()->cookie()
and cookies
.
Cookies can store key value in client system and its send back the cookies with every request so server can identify the user or session.
Why cookies are useful ?
Cookies are very useful for every website because without cookies server will unable to maintain the session for a request response. For example when we make a request to a website server, server sent response to user and the close the connection so here for next request server doesn’t know about the request is from same browser or client or it’s from different client. Therefore here cookies play the role to send some information by which server can identify it’s from same browser.
If you look at server side languages each language creates its own cookie to create the session as below
we can use below method to set the cookie in laravel
//Method 1
Cookie::queue(key, value, time);
//Method 2
$cookie = cookie('name', 'value', 10);
return response(view("welcome"))->cookie($cookie);
and to get the cookies back
//Method 1
Cookie::get('key');
//Method 2
return $request->cookie('key');
Let’s understand Set and Get Cookies in Laravel with example
Method 1 : Set and get cookies
In this method we will get and set cookies using the queue
and cookie
class to get the values so first create a route as follow
<?php
use Illuminate\Support\Facades\Route;
Route::get('/set-cookie',function(){
Cookie::queue("name", "readerstacks.com", 600);
return "cookie set successfully";
});
Route::get('/get-cookie',function(){
echo Cookie::get("name");
return "cookie get successfully";
});
Method 2 : Set and get cookies using request and response
In this method we will get and set cookies using the request
and response
method
<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;
Route::get('/set-cookie',function(Request $request){
$cookie = cookie('name', 'readerstacks', 600);
return response(view("welcome"))->cookie($cookie);
});
Route::get('/get-cookie',function(Request $request){
echo $request->cookie("name");
return "cookie get successfully";
});
Also Read : How to set and get cookies in angular using package ?