代码之家  ›  专栏  ›  技术社区  ›  s_h

设置国家/地区值的Laravel全球中间件在其逻辑中失败

  •  0
  • s_h  · 技术社区  · 7 年前

    我正在开发一个Laravel全球中间件,以便在web访问者访问网站时在Cookie中设置国家值。

    因此,我创建了以下函数:

    public function handle($request, Closure $next)
    {
        if(!$request->cookies->has('geo'))
        {
            if (!$request->cookies->has('geo') && GeoIP()->getLocation()->iso_code !== null) {
                //find customer IP location
                $code = strtolower(GeoIP()->getLocation()->iso_code);
                // creates a cookie with iso_code value
                $cookie = cookie('geo', $code, 600);
                //move to page
                return $next($request)->cookie($cookie);
            }
            else{
                return response()->view('static.select-country');
                //move to page
                return $next($request);
            }
        }
        if ($request->cookies->has('geo')) {
            //move to page
            return $next($request);
        }
    }
    

    1-如果cookie“geo”为空:

    2-如果cookie geo不是空代码:($request->cookies->has('geo'))

    • 访问者已经有一个cookie->移到第页。

    (我对第2步的想法是针对已有国家/地区的现有客户(已有一个具有该值的cookie),但他们希望在static.select-country视图中手动更改国家/地区,并避免GeoIP探测器被循环1覆盖。)

    我的问题:此时,当客户在static.select-country视图中手动选择时,它会移动到主页:

    • 但是应用程序使用GeoIP检测器分配cookie,而不是考虑客户手动选择的国家(在static.select country中创建的cookie)。
    1 回复  |  直到 7 年前
        1
  •  1
  •   Morilog    7 年前

    您可以为选择国家/地区页面创建路由,并在上面的中间件中忽略该路由。然后每个人都可以访问该页面,从列表中选择自己的国家,并在cookie中设置国家代码。

    if ($request->is('YOUR_ROUTE_PATH')) {
       return $next($request);
    }
    
    推荐文章