【问题标题】:Set cookie when the website opened first time in Laravel在 Laravel 中首次打开网站时设置 cookie
【发布时间】:2021-03-25 03:13:52
【问题描述】:

我正在使用 cookie 编写本地化。本地化适用于 cookie,但我想为第一次打开网站的人设置默认语言。因此,我为此创建了一个中间件并在路由中间件中注册:

public function handle(Request $request, Closure $next)
{
    get_cookie('lang') ?? set_cookie('lang', 'az');

    return $next($request);
}

get_cookieset_cookie 来自自定义助手:

if (!function_exists('get_cookie')) {
    function get_cookie($name)
    {
        return Cookie::get($name);
    }
}

if (!function_exists('set_cookie')) {
    function set_cookie($name, $value)
    {
        return Cookie::queue($name, $value, time() * 360 * 60);
    }
}

问题是当我第一次打开网站时它设置了 cookie,但它没有显示带有 cookie 的网站。但是,我第二次打开网站时,它会显示带有 cookie 的网站。 我在谷歌上搜索并在堆栈溢出中发现了这个:

if($request->hasCookie('lang')) {
    return $next($request);    
}

$response = $next($request);
return $response->withCookie(cookie()->forever('lang', 'az'));

但这对我不起作用,我认为它适用于旧版本的 laravel。我假设,我以错误的方式使用中间件,但我没有弄清楚。任何建议将不胜感激。

编辑: 我将中间件的位置 $routeMiddleware 更改为 $middlewareGroups。我认为 AddQueuedCookiesToResponse 中间件必须在该中间件列表中。但是,这似乎没有帮助。也许,列表中必须有另一个中间件?

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\SetLanguage::class,
        ],

        'api' => [
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

【问题讨论】:

  • 你必须确保这个中间件在使用 lang cookie 的中间件之前运行
  • 我将中间件的位置 $routeMiddleware 更改为 $middleware ,甚至放入数组的第一个元素中。但是,它没有用。

标签: php laravel cookies


【解决方案1】:

我没有设法让它与 cookie 一起工作。所以,我只是简单地使用会话而不是 cookie。因此,在中间件中,我将 lang 变量设置为 session。

public function handle(Request $request, Closure $next)
{
    if(!$request->session()->get('lang')) {
        session(['lang' => 'az']);
    }

    return $next($request);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 2019-10-25
    • 2019-01-13
    • 2022-01-26
    • 1970-01-01
    相关资源
    最近更新 更多