Laravel 5.2:如果设置了cookie,则通过刀片检索cookie也会返回null

时间:2016-08-20 09:37:38

标签: cookies laravel-5.2 laravel-blade

我通过Javascript

设置了一个Cookie FileUploader multipart = new FileUploader(url); File file = new File("path"); multipart.addFilePart("file", file); File image = new File("imgPath"); multipart.addFilePart("image", image); multipart.addFormField("userid", userId); String response = multipart.finish();
my_cookie

通过Chrome Cookie检查器我看到cookie的值为1。

通过Laravel Blade我试过了:

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

@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

unset

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

3 个答案:

答案 0 :(得分:22)

你可以使用

App\Http\Middleware\EncryptCookies的字段$except可满足您的需求。

中间件的代码看起来像这样

<?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'
   ];
}

现在您可以使用Cookie::get('my_cookie')request()->cookie('my_cookie')进行检索

答案 1 :(得分:11)

从评论移动:只有laravel创建的cookie才能通过laravel处理。尝试原生cookie $ _COOKIE。或者尝试通过laravel创建cookie然后dd($ _ COOKIE)你会发现它与由本机PHP创建的cookie完全不同

答案 2 :(得分:4)

这是因为laravel加密了他们的cookie。您可以不包含EncryptCookies中间件来处理cookie,而这些cookie并不是由laravel设置的。从\App\Http\Middleware\EncryptCookies::class

中的$middlewareGroups移除app\Http\Kernel.php