Home Backend Development PHP Tutorial About the use of cookies in Laravel5

About the use of cookies in Laravel5

Jun 13, 2018 am 11:35 AM
cookie

This article mainly introduces the use of cookies in Laravel5. Friends who need it can refer to it

When I used cookies in the Laravel framework today, I encountered some problems and I was confused for more than half an hour. During this period, I studied the implementation class of Cookie and also found a lot of information on the website, including Q&A. Discovery did not solve the problem. The answers on the Internet are plagiarized and reposted from each other. In fact, it is of no use. Fortunately, in the end, I found a solution. In the spirit of being responsible for the vast number of Laravel enthusiasts and developers, and also hoping that everyone will avoid detours when using cookies, I will contribute the setting and reading methods of cookies in Laravel here for everyone to criticize and correct.

Overview

The addition of Cookie is actually very simple. Use Cookie::make() directly. Before using the method, you need to Introduce the Cookie facade use Illuminate\Support\Facades\Cookie;, so that the Cookie setting can be completed (of course, it can be automatically loaded through the namespace without introducing the direct \Cookie use).

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

1

2

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

echo Cookie::get('test');

Copy after login

If you follow this similar answer to test Cookie, you will definitely find that the value set to the cookie is always null. If multiple tests fail, you will wonder if there is something wrong with your Laravel framework!

In fact, when using Cookies in the Laravel framework, you have to mention Response and Request. Developers who often use browsers to debug programs may have noticed that both the Response Headers and Request Headers of the request address contain cookie information. That's right, if you use cookies in the Laravel framework, you can't do without Response and Request. Let's introduce the correct way to add and obtain cookies.

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

Route::get('cookieset', function()

{

 $foreverCookie = Cookie::forever('forever', 'Success');

 $tempCookie = Cookie::make('temporary', 'Victory', 5);//参数格式:$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'));

});

//先上一个demo写入cookie

$cookie = \Cookie('cookie_name', 'value', 5);

  $data = ['title'=>'hello world'];

  return \response()

   ->view('home.hello', $data)

   ->cookie($cookie);

Copy after login

2. Cookie storage array:

1

2

3

4

5

6

7

8

9

10

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'));

});

Copy after login

Let’s talk about laravel’s cookies in detail

Add Cookie

#For example, we need to set a cookie value of "Hello, Laravel" in the controller and set the validity period to 10 minutes. It is recommended to use the cookie queue method Cookie::queue() here, because the cookie will be automatically added to the response:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<?php

namespace 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(&#39;test&#39;, &#39;Hello, Laravel&#39;, 10);//如果不适用上面的use Cookie,这里可以直接调用 \Cookie

  return view(&#39;index&#39;);

 }

}

Copy after login

See if there are too many Response Headers A set-cookie record is created. Of course, if you are using Response, you can directly use the withCookie() method in Response to add cookies to the response:

1

2

3

4

5

6

7

public function index()

{

 //$response = new Response();

 $cookie = Cookie::make(&#39;test&#39;, &#39;Hello, Laravel&#39;, 10);

   return \Response::make(&#39;index&#39;)->withCookie($cookie);

 //return $response->make(&#39;index&#39;)->withCookie($cookie);

}

Copy after login

To set a permanent For non-expired cookie values, you can use the Cookie::forever() method:

1

Cookie::forever(&#39;test&#39;, &#39;Hello, Laravel&#39;);

Copy after login

Cookie itself does not provide this method, because the appearance of Cookie is composed of\ Illuminate\Cookie\CookieJar is provided, so Cookie can use the methods in this class. Attached here is the source code of the queue() method:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

/**

* 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, &#39;make&#39;], func_get_args());

 }

 $this->queued[$cookie->getName()] = $cookie;

}

Copy after login

From the source code, we can know that the queue() method is actually the make() method called.

Note: Some friends have proposed the method of injecting cookies into the returned view. return view('index')->withCookie($cookie). Personal test is invalid. It is recommended to use queue()

Get Cookie

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

1

2

3

4

5

public function index(Request $request)

{

 $cookie = $request->cookie(&#39;test&#39;);

 dump($cookie);

}

Copy after login

If you want to get the value of all cookies, you can use no parameters. Method:

1

2

3

4

5

public function index(Request $request)

{

 $cookies = $request->cookie();

 dump($cookies);

}

Copy after login

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

1

2

3

4

5

array:3 [▼

 "XSRF-TOKEN" => "CDSXUUYYHJHGDDFGHJAxPNNsVxLHGTRYUGJ"

 "laravel_session" => "870a775gthhgef0b9f357edc6r6587878999876556"

 "test" => "Hello, Laravel"

]

Copy after login

When we need to use it on the client, getting the value of Cookie is not the case. First of all, the data we transmit to the client by responding to withCookie($cookie) is not a string, but a cookie object:

1

2

3

4

5

6

7

8

9

Cookie {#1490 ▼

 #name: "test"

 #value: "Hello, Laravel"

 #domain: null

 #expire: 1493791460

 #path: "/"

 #secure: false

 #httpOnly: true

}

Copy after login

Get the value, The Cookie class provides a getValue() method to get it. For example, edit the code in the template:

1

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

Copy after login

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

Hello, Laravel

Clear Cookie

The method of clearing Cookie is relatively simple. The principle is the same as setting Cookie, except that the expiration time is set to the past. Here you also need to add Cookie to the HTTP Response, using the make() or forget() method:

1

2

$cookie = Cookie::forget(&#39;test&#39;);

return Redirect::route(&#39;index&#39;)->withCookie($cookie);

Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone’s learning. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Using Passport to implement Auth authentication in Laravel5.5

About the use of the date and time processing package Carbon in Laravel

The above is the detailed content of About the use of cookies in Laravel5. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
How to Fix Roblox 403 Forbidden Error on Google Chrome How to Fix Roblox 403 Forbidden Error on Google Chrome May 19, 2023 pm 01:49 PM

Many Windows users have recently encountered an unusual error called Roblox403 Forbidden Error while trying to access website URLs in Google Chrome browser. Even after restarting the Chrome app multiple times, they were unable to do anything. There could be several potential causes for this error, some of which we've outlined and listed below. Browsing history and other cache of Chrome and corrupted data Unstable internet connection Incorrect website URLs Extensions installed from third-party sources After considering all the above aspects, we have come up with some fixes that can help users resolve this issue. If you encounter the same problem, check out the solutions in this article. Fix 1

Where are cookies stored? Where are cookies stored? Dec 20, 2023 pm 03:07 PM

Cookies are usually stored in the cookie folder of the browser. Cookie files in the browser are usually stored in binary or SQLite format. If you open the cookie file directly, you may see some garbled or unreadable content, so it is best to use Use the cookie management interface provided by your browser to view and manage cookies.

Where are the cookies on your computer? Where are the cookies on your computer? Dec 22, 2023 pm 03:46 PM

Cookies on your computer are stored in specific locations on your browser, depending on the browser and operating system used: 1. Google Chrome, stored in C:\Users\YourUsername\AppData\Local\Google\Chrome\User Data\Default \Cookies etc.

Where are the mobile cookies? Where are the mobile cookies? Dec 22, 2023 pm 03:40 PM

Cookies on the mobile phone are stored in the browser application of the mobile device: 1. On iOS devices, Cookies are stored in Settings -> Safari -> Advanced -> Website Data of the Safari browser; 2. On Android devices, Cookies Stored in Settings -> Site settings -> Cookies of Chrome browser, etc.

How cookies work How cookies work Sep 20, 2023 pm 05:57 PM

The working principle of cookies involves the server sending cookies, the browser storing cookies, and the browser processing and storing cookies. Detailed introduction: 1. The server sends a cookie, and the server sends an HTTP response header containing the cookie to the browser. This cookie contains some information, such as the user's identity authentication, preferences, or shopping cart contents. After the browser receives this cookie, it will be stored on the user's computer; 2. The browser stores cookies, etc.

What are the dangers of cookie leakage? What are the dangers of cookie leakage? Sep 20, 2023 pm 05:53 PM

The dangers of cookie leakage include theft of personal identity information, tracking of personal online behavior, and account theft. Detailed introduction: 1. Personal identity information is stolen, such as name, email address, phone number, etc. This information may be used by criminals to carry out identity theft, fraud and other illegal activities; 2. Personal online behavior is tracked and analyzed through cookies With the data in the account, criminals can learn about the user's browsing history, shopping preferences, hobbies, etc.; 3. The account is stolen, bypassing login verification, directly accessing the user's account, etc.

Does clearing cookies have any impact? Does clearing cookies have any impact? Sep 20, 2023 pm 06:01 PM

The effects of clearing cookies include resetting personalization settings and preferences, affecting ad experience, and destroying login status and password remembering functions. Detailed introduction: 1. Reset personalized settings and preferences. If cookies are cleared, the shopping cart will be reset to empty and products need to be re-added. Clearing cookies will also cause the login status on social media platforms to be lost, requiring re-adding. Enter your username and password; 2. It affects the advertising experience. If cookies are cleared, the website will not be able to understand our interests and preferences, and will display irrelevant ads, etc.

Detailed explanation of where browser cookies are stored Detailed explanation of where browser cookies are stored Jan 19, 2024 am 09:15 AM

With the popularity of the Internet, we use browsers to surf the Internet have become a way of life. In the daily use of browsers, we often encounter situations where we need to enter account passwords, such as online shopping, social networking, emails, etc. This information needs to be recorded by the browser so that it does not need to be entered again the next time you visit. This is when cookies come in handy. What are cookies? Cookie refers to a small data file sent by the server to the user's browser and stored locally. It contains user behavior of some websites.

See all articles