首页 > 解决方案 > URL 明智的 cookie laravel

问题描述

我创建了一个实时项目。到目前为止,我正在使用 sumdomain 管理语言,例如en.example.comtr.example.com等。因此,由于单独的子域,我在 cookie 管理方面没有问题,例如随机 user_id cookie

但是现在我想使用诸如example.com/en、example.com/tr等 URL 来管理语言,现在问题是我不希望example.com/en的user_idexample.com/tr覆盖分开,因为它在子域的情况下。

那么有什么办法可以解决这个问题吗?我已经尝试过SESSION_DOMAIN的东西,但不知道我是否正确。

标签: laravelsessioncookiessubdomainmultilingual

解决方案


通常你可以设置cookie路径,config/sessions.php但问题是(我假设)区域设置是根据每个请求确定的,这使得这不可能。另一种方法是StartSession用您自己的自定义中间件替换中间件,例如

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Illuminate\Session\Middleware\StartSession;

class LocaleAwareStartSession extends StartSession {

    public function getSession(Request $request) {
         $locale = <determine locale here>;
         config([ 'session.cookie' => config('session.cookie').$locale ]);
         return parent::getSession();
    }
}

然后,您需要更换中间件Kernel.php

protected $middlewareGroups = [
        'web' => [
            // ...
            LocaleAwareStartSession::class, // instead of StartSession::class
            // ...
        ],

这应该足够早地设置会话 cookie 名称,以便为每个语言环境使用不同的 cookie 名称。$request->route()->parameter('locale')假设您定义了locale在匹配路由中调用的参数,您可以(通常)获取语言环境。


推荐阅读