Laravel Cookie Example | Set and Get Cookie in Laravel

Hello Aertisan

In this tutorial i will discuss about Laravel Cookie. Do you know what is a Cookie and how its works? Cookies play an important role while dealing a user’s session on a web application. In this chapter, you will learn about working with cookies in Laravel based web applications.

An HTTP cookie (also called web cookieInternet cookiebrowser cookie, or simply cookie) is a small piece of data sent from a website and stored on the user's computer by the user's web browser while the user is browsing.

Sometime we need to create cart system in our web application. This feature we can develope using Session. But in think it will be more trustable than using session if you use Cookie. 

Cause if you use session and close your browser then your session data will lost. But if you use Cookie then it can not be lost untill you remove it from your browser. So you can do same thing using Cookie what you do using session.

In laravel the cookie function creates a new cookie instance. In this tutorial we will see how we can create that mean set cookie and then get that cookie in laravel. See the below example.

To simply set and get cookie in laravel follow that code.

$cookie = cookie('name', 'value', $minutes);

 

Look, cookie take three parameter, first is cookie_name, second is its value that mean data and third is its life_time. So now simply create it.

public function setCookie(Request $request) {

    Cookie::queue('name', $request->test, 10);

    return view('home');
}

 

Here Cookie::queue($cookie_name, $data, $life_time_of_this_cookie);

And simply print cookie where you want to show data

{{ Cookie::get('name') }}

 

Hope it can help you.