Laravel 5.2 Variable in a route group

I built a website with several languages ​​and in order to display the correct language, I am doing something like this:

routes.php:

Route::group(['middleware' => 'web', 'prefix' => '{locale}'], function () { Route::auth(); Route::get('home', ' HomeController@index '); etc... }); 

My controllers:

 <?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Http\Requests; use Illuminate\Http\Request; class HomeController extends Controller { public function index($locale) { app()->setLocale($locale); return view('home'); } } 

As you can see, I get a local variable from my prefix, and I install the application locally inside each function.

This works fine, but I wonder if there is a better way to do this? I feel this is a little redundant.

I thought to configure the local application directly in the route group. Something like that:

 Route::group(['middleware' => 'web', 'prefix' => '{locale}'], function ($locale) { app()->setLocale($locale); Route::auth(); Route::get('home', ' HomeController@index '); ... }); 

But this obviously does not work. Has anyone already dealt with such things?

+5
source share
2 answers

I found a solution a couple of days ago, I would like to share it here.

The answer is actually quite simple: middleware!

First create a new middleware (in my case LocaleMiddleware)

 class LocaleMiddleware { public function handle($request, Closure $next) { app()->setLocale($request->locale); return $next($request); } } 

Then you can simply add your middleware to the web middleware group in App / Kernel.php

 protected $middlewareGroups = [ 'web' => [ ... \App\Http\Middleware\VerifyCsrfToken::class, \App\Http\Middleware\LocaleMiddleware::class, ], 'api' => [ 'throttle:60,1', ], ]; 

Hope this helps!

+1
source

Use this package that helped me with the localization https://github.com/mcamara/laravel-localization

0
source

Source: https://habr.com/ru/post/1243280/


All Articles