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

About the use of cookies in Laravel5

不言
Release: 2023-03-31 22:14:02
Original
2208 people have browsed it

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:

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():

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:

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:

<?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:

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:

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:

/**
* 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:

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:

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:

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:

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:

<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:

$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!

Related labels:
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
Latest Issues
laravel5 namespace problem
From 1970-01-01 08:00:00
0
0
0
How do you use smarty to integrate laravel5?
From 1970-01-01 08:00:00
0
0
0
Merge requirejs in laravel5
From 1970-01-01 08:00:00
0
0
0
vendor - laravel5 problems after cloning from git
From 1970-01-01 08:00:00
0
0
0
laravel5 cannot start
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template