search
HomeBackend DevelopmentPHP TutorialAbout 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:

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

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

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

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

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

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

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;
}

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

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

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"
]

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
}

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>

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

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
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
What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

How do you optimize PHP applications for performance?How do you optimize PHP applications for performance?May 08, 2025 am 12:08 AM

TooptimizePHPapplicationsforperformance,usecaching,databaseoptimization,opcodecaching,andserverconfiguration.1)ImplementcachingwithAPCutoreducedatafetchtimes.2)Optimizedatabasesbyindexing,balancingreadandwriteoperations.3)EnableOPcachetoavoidrecompil

What is dependency injection in PHP?What is dependency injection in PHP?May 07, 2025 pm 03:09 PM

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

Best PHP Performance Optimization TechniquesBest PHP Performance Optimization TechniquesMay 07, 2025 pm 03:05 PM

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

PHP Performance Optimization: Using Opcode CachingPHP Performance Optimization: Using Opcode CachingMay 07, 2025 pm 02:49 PM

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

See all articles

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool