我们正在使用IP2LOCATIONLARAVEL获取访客的国家代码。如果访问者的IP来自伊朗(ISO国家代码= 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);
}
}
然后我们更新了app / Providers / RouteServiceProvider.php:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
class RouteServiceProvider extends ServiceProvider
{
protected $namespace = 'App\Http\Controllers';
public function boot()
{
parent::boot();
}
public function map(Request $request)
{
$this->mapApiRoutes();
$this->mapWebRoutes($request);
}
protected function mapWebRoutes(Request $request)
{
if(in_array($request->segment(0), config('app.other_locale'))){
$locale = $request->segment(0);
}else{
$locale = null;
}
Route::group([
'middleware' => 'web',
'namespace' => $this->namespace,
'prefix' => $locale
], function ($router) {
require base_path('routes/web.php');
});
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
}
localhost / laravel / public / fa是404错误页面。我们如何更新
<html lang="{{ app()->getLocale() }}">
在我们的刀片文件中,如果访客的国家代码是IR?
答案 0 :(得分:0)
您确定已在文件kernel.php中添加了中间件
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\LocaleHandler::class,
...]