Laravel 5.2: retrieving a cookie via blade returns null also if cookie is set

落爺英雄遲暮 提交于 2020-01-13 10:12:20

问题


I set a cookie my_cookie via Javascript

   function createCookie(name, value, days) {
      var expires;
      if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires="+date.toUTCString();
      }
      else {
        expires = "";
      }
      document.cookie = name+"="+value+expires+"; path=/";
   }

   ....
   createCookie('my_cookie', 1, 365);
   ....

Via Chrome Cookie Inspector I see that the cookie is created with value 1.

Via Laravel Blade I tried:

 @if (Cookie::get('my_cookie') !== null) // or Cookie::get('my_cookie') == 1 or Cookie::get('my_cookie') == '1'
      <p>set</p>
 @else
      <p>unset</p>
 @endif

that writes unset

 @if (request()->cookie('my_cookie') == '1') // or @if (request()->cookie('my_cookie') == 1)
      <p>set</p>
 @else
      <p>unset</p>
 @endif

The result is always unset.


回答1:


Move from comment: Only cookie created by laravel can handle by laravel. Try native cookie $_COOKIE. Or try create cookie by laravel then dd($_COOKIE) you'll see it totally different to cookie which created by native PHP




回答2:


You can use

App\Http\Middleware\EncryptCookies's field $except for your needs.

The code of the middleware will look like this

<?php

namespace App\Http\Middleware;

use Illuminate\Cookie\Middleware\EncryptCookies as BaseEncrypter;

class EncryptCookies extends BaseEncrypter
{
  /**
   * The names of the cookies that should not be encrypted.
   *
   * @var array
   */
   protected $except = [
      'my_cookie'
   ];
}

And now you can use Cookie::get('my_cookie') or request()->cookie('my_cookie') for retrieving it




回答3:


It's because laravel encrypts their cookies. You can just not include EncryptCookies middleware to work with cookies, which weren't being set by laravel. Remove \App\Http\Middleware\EncryptCookies::class from $middlewareGroups in app\Http\Kernel.php



来源:https://stackoverflow.com/questions/39052612/laravel-5-2-retrieving-a-cookie-via-blade-returns-null-also-if-cookie-is-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!