Patriot
Patriot

Reputation: 312

Returning a controller in Laravel 5.6 route file

I am trying to route a request to a controller method. When I do this it works:

Route::get('/path', 'controller@method');

I would like to set the locale before calling the controller. I tried different options and nothing works:

Route::get('/path', function(){
   desired_function();
   return action('controller@method');
});

and

Route::get('/path', function(){
   desired_function();
   return [
    'uses' => 'controller@method'
    ];
});

What am I missing?

Upvotes: 2

Views: 5198

Answers (1)

num8er
num8er

Reputation: 19372

1) Create a app/Http/Middleware/SetLocale.php with content:

<?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) Attach it to route:

Route::get('/path', 'controller@method')
       ->middleware('App\Http\Middleware\SetLocale');

or to route group:

Route::group([
  'middleware' => [
    'App\Http\Middleware\SetLocale'
  ]
], 
function() {

  Route::get('/path', 'controller@method');

});

if You want it to be used globally everywhere:

in 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
];

Upvotes: 1

Related Questions