About the use of cookies in Laravel5

Source: Internet
Author: User
This article mainly describes the use of cookies in the Laravel5, the need for friends can refer to the following

Today, when using cookies in the Laravel framework, I ran into a bit of a problem and was confused for half an hour. During the study of the cookie implementation class, we also found a lot of information on the website, including questions and answers. The discovery did not solve the problem. The answer on the Internet is to copy each other and reprint each other. It's not really useful. Fortunately, in the end, I found a way to refuse. Ben for the vast number of laravel enthusiasts and developers responsible for the spirit, but also hope that everyone in the use of cookies less detours, here in the Laravel cookie set up and read methods to contribute, for everyone to criticize correct.

Overview

The addition of cookies is very simple, directly using Cookie::make (), before using the method, you need to introduce a cookie façade use Illuminate\support\facades\cookie, so that you can complete the cookie settings ( Of course not introducing direct \cookie use can also be automatically loaded through the namespace).

However, how can we get the cookie value after setting it? Developers who have searched for the relevant questions must know that the answers on the web are all the same: Cookie::get (), and some even include the code:

Cookie::make (' Test ', ' Hello, World '), Echo cookie::get (' Test ');

If you test the cookie in a similar way, you will definitely find that the value of setting the cookie is always null. Many times the test is invalid, you will doubt your laravel frame is not a problem!

In fact, using cookies in the Laravel framework would have to mention response and request. Developers who frequently use browser debugging programs may notice that there is cookie information in the response headers and request headers of the requesting address. Yes, if you use cookies in the Laravel framework without response and request, here's how to add and get cookies correctly.

How to use Cookie::make (), Cookie::forever (), Cookie::get ():

Route::get (' Cookieset ', function () {$foreverCookie = Cookie::forever (' Forever ', ' Success '); $tempCookie = Cookie::make (' temporary ', ' Victory ', 5);//Parameter format: $name, $value, $minutes return Response::make ()->withcookie ($foreverCookie)- >withcookie ($tempCookie);}); Route::get (' CookieTest ', function () {  $forever = Cookie::get (' forever ');  $temporary = Cookie::get (' temporary ');  Return View::make (' CookieTest ', Array (' forever ' = $forever, ' temporary ' = ' = ' $temporary, ' variabletest ' = ' Works ');}); /First on a demo write Cookie$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 ');});

The following is a detailed discussion of Laravel's cookie specific how to play it

Add a cookie

For example, we need to set a "Hello, Laravel" cookie value in the controller and set the validity period to 10 minutes. It is recommended to 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 use above is not applicable Cookie, which can be directly called \cookie  return View (' Index ');}}

See if there is a Set-cookie record in response headers. Of course, if you are using response, you can add the cookie to the response directly using the Withcookie () method in 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 use the Cookie::forever () method:

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

The cookie itself does not provide the method, because the cookie's façade is provided by \illuminate\cookie\cookiejar, so the cookie can use the methods in that class. The source code for the queue () method is attached here:

/*** queue a cookie to send with the next response.** @param mixed* @return void*/public function Queue () {if (Head (func_g Et_args ()) instanceof Cookie) {  $cookie = Head (Func_get_args ());} else {  $cookie = Call_user_func_array ([$this, ' Make '], Func_get_args ()); } $this->queued[$cookie->getname ()] = $cookie;}

As you can tell from the source, the queue () method is actually called the Make () method.

Note: Some water friends propose a method of injecting a cookie on the returned view return view('index')->withCookie($cookie) , and the pro-test is invalid. We recommend using queue ()

Get cookies

As we mentioned in the overview, the use of cookies is inseparable from response and request. There are two levels of the value of the cookie, one for the server and the other for the client. If you want the server to get the value of the cookie, you need to get it from the request:

Public Function Index (Request $request) {$cookie = $request->cookie (' test '); dump ($cookie);}

If you want to get the value of all cookies, you can use the no-arguments method:

Public Function Index (Request $request) {$cookies = $request->cookie (); dump ($cookies);}

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

Array:3 ["Xsrf-token" = "Cdsxuuyyhjhgddfghjaxpnnsvxlhgtryugj" "laravel_session" and "=" 870a775gthhgef0b9f357edc6r6587878999876556 "" Test "=" Hello, Laravel "]

When we need to use it on the client side, it's not the case to get the cookie value. First, the data that we transmit to the client by responding to Withcookie ($cookie) is not a string, but a cookie object:

Cookie {#1490 #name: "Test" #value: "Hello, Laravel" #domain: null #expire: 1493791460 #path: "/" #secure: false #httpOn Ly:true}

To get the value, the cookie class provides a GetValue () method to fetch. For example, edit the code in the template:

<p>{{$cookie->getvalue ()}}</p>

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

Hello, Laravel.

Clearing cookies

The method of clearing cookies is simple, the same principle as setting cookies, just set the expiration time to the past. You also need to add cookies to the HTTP response, using the make () or Forget () methods:

$cookie = cookie::forget (' Test '), return Redirect::route (' index ')->withcookie ($cookie);

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

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.