【问题标题】:How to work with cookies in Laravel 5.2如何在 Laravel 5.2 中使用 cookie
【发布时间】:2016-03-22 09:01:31
【问题描述】:

我在一些点击事件上设置 cookie。然后在cookie中存储值之后,我想

  1. 检查 cookie 是否存在
  2. 获取 cookie 值

我通过参考 Laravel 官方文档开发了一个功能。控制台显示 cookie 已设置。但在那之后,我无法解决视图(刀片模板)的两点(在上面的列表中提到)。它总是显示(Cookie::get('cookie.clients'))'null'。但浏览器控制台显示该 cookie . 如果有人知道答案,将不胜感激。

这是我的代码。

控制器

use App\Client;
use App\Http\Requests;
use Illuminate\Http\Request;
use Validator;
use App\Http\Controllers\Controller;
use App\Repositories\ClientRepository;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;

class ClientController extends Controller
{
    public function cookieadd(Request $request, Client $client)
    {
        $clients = [];
        if (Cookie::get('cookie.clients') != null)
        {
            $clients = Cookie::get('cookie.clients');
        }
        array_push($clients, $client);

        Cookie::forever('cookie.clients', $clients);

        return redirect('/client');
    }
}

查看

@if (Cookie::get('cookie.clients') != null)
<p>cookie is set</p>
@else
<p>cookie isn't set</p>
@endif

【问题讨论】:

  • 你是在“一些点击事件”中通过javascript设置cookie,还是在你的Clientcontroller中调用cookieadd方法?
  • @Padarom,通过调用方法cookieadd()

标签: php laravel laravel-5.2


【解决方案1】:

您正在创建一个 cookie 对象,但您没有将其与响应一起发送。

您可以将其直接添加到控制器中的响应中

$cookie = Cookie::forever('cookie.clients', $clients);

return redirect('/client')->withCookie($cookie);

或者您可以将 cookie 排队并使用 AddQueuedCookiesToResponse 中间件将其自动添加到响应中。

Cookie::queue(Cookie::forever('cookie.clients', $clients));

return redirect('/client');

【讨论】:

    【解决方案2】:

    这是另一个视角。

    如果我理解正确,您已经使用 Javascript 在客户端设置 cookie,并且您想在服务器端获取它。

    Laravel 会加密它的 cookie,当你使用 $request-&gt;cookies() 时,你会得到解密后的值,从客户端检索 cookie 不会通过解密过程,我们会得到 nulls。我猜,我一直没能挖出合适的源代码:)

    您仍然可以使用原始 PHP $_COOKIE['cookie_clients'] 来检索客户端设置的 cookie。注意,. 被 PHP (as seen on php.net) 转换为 _。

    或者,您可以将感兴趣的 cookie 的名称添加到 Http/Middleware/EncryptCookies.php 中的 $except,这将允许您使用 $request-&gt;cookie() 的更多 Laravel 方法来获取它。

    我相信这里还有很多其他的方法可以绕过 Laravel,希望这能让你知道如果你不喜欢这两种方法,应该去哪里找。祝你好运。

    【讨论】:

      【解决方案3】:

      您是否尝试通过 Request 对象显示 cookie?

      $value = $request->cookie('name');
      

      查看 laravel 文档了解更多详情:https://laravel.com/docs/5.2/requests#cookies

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-12-25
        • 1970-01-01
        • 2018-08-10
        • 2016-06-02
        • 1970-01-01
        • 2017-11-12
        • 2016-06-05
        相关资源
        最近更新 更多