我正在尝试将请求路由到控制器方法。当我这样做时,它有效:
Route::get('/path', 'controller@method');
我想在调用控制器之前设置语言环境。我尝试了不同的选项,没有任何作用:
Route::get('/path', function(){
desired_function();
return action('controller@method');
});
和
Route::get('/path', function(){
desired_function();
return [
'uses' => 'controller@method'
];
});
我错过了什么?
答案 0 :(得分:1)
1)创建一个包含内容的app/Http/Middleware/SetLocale.php
:
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class SetLocale
{
public function handle(Request $request, Closure $next)
{
\App::setLocale('en'); // or get it from request
// or:
// $request->attributes->set('locale', 'en');
// in action: $request->get('locale');
return $next($request);
}
}
2)将其附加到路线:
Route::get('/path', 'controller@method')
->middleware('App\Http\Middleware\SetLocale');
或路由组:
Route::group([
'middleware' => [
'App\Http\Middleware\SetLocale'
]
],
function() {
Route::get('/path', 'controller@method');
});
如果您希望在全球各地使用它:
app/Http/Kernel.php
中的:
/**
* The application's global HTTP middleware stack.
*
* @var array
*/
protected $middleware = [
...
'App\Http\Middleware\SetLocale' // add it to end of array
];