Use of cookies in Laravel5, laravel5cookie

Source: Internet
Author: User
Tags set cookie

Use of cookies in Laravel5, laravel5cookie

Today, when I used cookies in the Laravel framework, I encountered some problems and was confused for more than half an hour. during this period, I studied Cookie implementation and found a lot of information on the website, including Q &. The problem was not solved. The answers on the Internet are copied and reproduced from each other. In fact, it is useless. Fortunately, I finally found a solution. Alibaba Cloud is responsible for the majority of Laravel enthusiasts and developers. We also hope that we will avoid detours when using cookies. Here we will contribute to the Cookie setting and reading methods in Laravel, for criticism and correction.

Overview

Cookie addition is actually very simple and can be directly usedCookie::make()Before using this method, you must introduce the Cookie facade.use Illuminate\Support\Facades\Cookie;In this way, you can complete the Cookie settings (of course, directly \ Cookie can be automatically loaded through the namespace without introducing it ).

However, how can we get the Cookie value after setting it? Developers who have searched for related questions certainly know that the answers on the Internet are the same:Cookie::get(), And some even include the Code:

Cookie::make('test', 'hello, world', 10);echo Cookie::get('test');

If you test the Cookie according to the similar answer, you will surely find that the cookie value is always null. If multiple tests are ineffective, you may wonder if your Laravel framework is faulty!

In fact, when using cookies in the Laravel framework, we have to mention Response and Request. Developers who often use browsers to debug programs may have noticed thatResponse HeadersAndRequest HeadersContains cookie information. If you are not required to use cookies in the Laravel framework, we will introduce how to correctly add and obtain cookies.

1. How to Use Cookie: make (), Cookie: forever (), Cookie: get:

Route: get ('cookieset', function () {$ foreverCookie = Cookie: forever ('forever', 'success '); $ tempCookie = Cookie :: make ('temporary ', 'My name is fantasy', 5); // parameter format: $ name, $ value, $ minutes return Response: make () -> withCookie ($ foreverCookie)-> withCookie ($ tempCookie) ;}); Route: get ('cookietest ', function () {$ forever = Cookie :: get ('forever'); $ temporary = Cookie: get ('tempory'); return View: make ('cookietest ', array ('forever' => $ forever, 'tempory' => $ temporary, 'variabletest' => 'it works '));});
// Write the cookie in the previous demo
$ Cookie = \ Cookie ('cookie _ name', 'value', 5); $ data = ['title' => 'Hello world']; return \ response () -> view ('home. hello ', $ data)-> cookie ($ cookie );

2. Cookie storage array:

Route::get('cookieset', function(){    $user_info = array('name'=>'laravel','age'=>12);    $user = Cookie::make('user',$user_info,30);    return Response::make()->withCookie($user);});Route::get('cookietest', function(){    dd(Cookie::get('user'));});

Next, let's take a look at laravel cookies.

Add Cookie

For example, we need to set a "Hello, Laravel" cookie value in the Controller and set the validity period to 10 minutes. We recommend that you use the cookie queue method.Cookie::queue()Because the Cookie is automatically added to the response:

<? Phpnamespace App \ Http \ Controllers; use Cookie; use App \ Http \ Controllers \ Controller; class DashboardController extends Controller {/*** Show the application index. ** @ return Response */public function index () {Cookie: queue ('test', 'Hello, Laravel ', 10); // if the above use Cookie is not applicable, \ Cookie return view ('index') can be directly called here ');}}

Check whether there is an additional one in Response Headers.set-cookieRecord. Of course, if you are using Response, you can directly usewithCookie()Method to add the cookie to the response:

public function index(){    //$response = new Response();    $cookie = Cookie::make('test', 'Hello, Laravel', 10);
   return \Response::make('index')->withCookie($cookie); //return $response->make('index')->withCookie($cookie);}

To set a cookie value that never expires, you can useCookie::forever()Method:

Cookie::forever('test', 'Hello, Laravel');

Cookie itself does not provide this method, because the Cookie facade is composed\Illuminate\Cookie\CookieJarProvided, So cookies can use the methods in this class. Attached herequeue()Source code of the method:

/*** Queue a cookie to send with the next response.** @param  mixed* @return void*/public function queue(){    if (head(func_get_args()) instanceof Cookie) {        $cookie = head(func_get_args());    } else {        $cookie = call_user_func_array([$this, 'make'], func_get_args());    }    $this->queued[$cookie->getName()] = $cookie;}

We can find out from the source code,queue()The method is actually called.make()Method.

Note: Some friends have suggested how to inject cookies Into the returned view.return view('index')->withCookie($cookie), The test is invalid. Recommendedqueue()

Get Cookie

As mentioned in the overview, the use of cookies is inseparable from Response and Request. There are two levels to obtain the Cookie value: one is the server and the other is the client. If you want the server to obtain the Cookie value, you need to get it from the Request:

public function index(Request $request){    $cookie = $request->cookie('test');    dump($cookie);}

If you want to obtain the values of all cookies, you can use the method of not passing parameters:

public function index(Request $request){    $cookies = $request->cookie();    dump($cookies);}

 

To access the address again, we will get an array of all cookie values, including the test we just set:

array:3 [▼  "XSRF-TOKEN" => "CDSXUUYYHJHGDDFGHJAxPNNsVxLHGTRYUGJ"  "laravel_session" => "870a775gthhgef0b9f357edc6r6587878999876556"  "test" => "Hello, Laravel"]

 

This is not the case when we need to obtain the Cookie value from the client. First, we use the responsewithCookie($cookie)The data transmitted to the client is not a string, but a cookie object:

Cookie {#1490 ▼  #name: "test"  #value: "Hello, Laravel"  #domain: null  #expire: 1493791460  #path: "/"  #secure: false  #httpOnly: true}

 

Obtain the value. The Cookie class providesgetValue(). For example, edit the code in the template:

<div>{{ $cookie->getValue() }}</div>

When you refresh the page again, you will get the set cookie value of test:

Hello, Laravel
Clear Cookie

The method of clearing a Cookie is relatively simple. The principle is the same as setting a Cookie, but the expiration time is set to the past. Add the Cookie to the HTTP Response.make()Orforget()Methods:

$cookie = Cookie::forget('test');return Redirect::route('index')->withCookie($cookie);

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.