我正在使用laravel 5.1,我尝试更新app文件中的区域设置,如下所示: 在Locale Middleware文件中:
...
public function handle($request, Closure $next)
{
if(Session::has('locale'))
{
$lang = Session::get('locale');
App::setLocale($lang);
}
return $next($request);
}
对此有任何想法??
答案 0 :(得分:6)
Oooof最后两小时后><' ! 它是中间件中locale类的行位置 - .-'!!! 我在最后一行设置如下:
...
...
\App\Http\Middleware\VerifyCsrfToken::class,
\App\Http\Middleware\Locale::class,
];
一切都很好,工作正常!谢谢大家:))))
答案 1 :(得分:2)
我找到的唯一解决方案是在中间件的构造方法中设置locale,如下所示:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\Request;
class Localization
{
protected $app;
public function __construct(Application $app, Request $request)
{
if($locale = $request->header('Content-Language')){
if(in_array($locale, ['en', 'fa'])){
$app->setLocale($locale);
}
}
}
/**
* Handle an incoming request.
*
* @param Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request);
}
}
用♥♥♥尝试超过2小时!
答案 2 :(得分:0)
谢谢,
:)我遇到了同样的问题,解决方案是将中间件放在文件中 受保护的$ middleware = []
部分中的 App \ Http \ Kernel.php\App\Http\Middleware\VerifyCsrfToken::class,
\App\Http\Middleware\myNewMiddleware::class,
];
答案 3 :(得分:0)
我已经解决了以下问题:
1步。创建了一个中间件。 php artisan make:middleware SetLocale
2步骤。更新了中间件文件。档案:app/Http/Middleware/SetLocale.php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
class SetLocale
{
private $locales = ['ar', 'en'];
// ...
public function handle($request, Closure $next, $locale)
{
if (array_search($locale, $this->locales) === false) {
return redirect('/');
}
App::setLocale($locale);
return $next($request);
}
}
3步骤。将我的新中间件附加到app/Http/Kernel.php
$routeMiddleware
数组。
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
// ...
protected $routeMiddleware = [
// ...
'locale' => \App\Http\Middleware\SetLocale::class,
];
}
4个步骤。我在routes/web.php
文件中使用了中间件。
Route::group(['prefix' => 'ar', 'namespace' => 'Arabic', 'middleware' => 'locale:ar'], function() {
Route::get('/', 'PashtoHomeController@index')->name('arHome');
// ...
});
Route::group(['prefix' => 'en', 'namespace' => 'English', 'middleware' => 'locale:en'], function() {
Route::get('/', 'PashtoHomeController@index')->name('enHome');
// ...
});
Route::get('/', function() {
return redirect()->route('arHome');
});