Php 如何更改刀片文件的区域设置

Php 如何更改刀片文件的区域设置,php,laravel,Php,Laravel,我们使用IP2LocationLavel获取访客的国家代码。如果访问者的IP来自伊朗(ISO country code=IR),则blade.php中html标记的lang属性必须设置为“fa”,否则设置为“en” 首先,我们在config/app.php中添加了这一行: 'locale' => 'en', // we added: 'other_locale' => ['fa-IR'], 我们还创建了一个中间件,并将其正确地添加到app/Http/kernel.php中 <

我们使用IP2LocationLavel获取访客的国家代码。如果访问者的IP来自伊朗(ISO country code=IR),则blade.php中html标记的lang属性必须设置为“fa”,否则设置为“en”

首先,我们在config/app.php中添加了这一行:

'locale' => 'en',
// we added:
'other_locale' => ['fa-IR'],
我们还创建了一个中间件,并将其正确地添加到app/Http/kernel.php中

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Foundation\Application;
use Ip2location\IP2LocationLaravel\Facade\IP2LocationLaravel;

class LocaleHandler
{
    public function __construct(Application $app, Request $request) {
        $this->app = $app;
        $this->request = $request;
    }

    public function handle($request, Closure $next)
    {
        if (app()->getLocale()=='fa'){
            if(in_array($request->segment(0), config('app.other_locale'))){
                $this->app->setLocale($request->segment(0));
            }else{
                $this->app->setLocale(config('app.locale'));
            }
        }

        return $next($request);
    }
}

您确实在web文件kernel.php中添加了中间件

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\LocaleHandler::class,
...]

很难说你真正想要实现什么。您应该在PHP代码中设置有效的语言环境,在Blade中,您只需按照所示显示它。如果来访者是伊朗人,我想把他带到法国。我有一个if-else(用于检查访问者国家/地区代码),但它不起作用:setLocale。看看答案,可能是您的中间件从未应用过的问题“/”是en,但“/fa”仍然是错误404,而不是“fa”注意:Route::get(“/”,function(){return view('welcome');});
<html lang="{{ app()->getLocale() }}">
protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\LocaleHandler::class,
...]