返回Laravel 5.6路由文件中的控制器

时间:2018-04-22 23:27:44

标签: laravel

我正在尝试将请求路由到控制器方法。当我这样做时,它有效:

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'
    ];
});

我错过了什么?

1 个答案:

答案 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
];