Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.2 Variable in a group of route

I built a multi language website and in order to display the correct language I do 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 the local variable from my prefix and I set the app local within each functions.

This is perfectly working but I am wondering if there is a better way to do it? I feel it's a little redundant..

I was thinking to set the app local directly in the route group. Something like this:

Route::group(['middleware' => 'web', 'prefix' => '{locale}'], function ($locale) {

app()->setLocale($locale);

Route::auth();
Route::get('home', 'HomeController@index');

...
});

But this is evidently not working.. Does someones has dealt with this kind of things already ?

like image 360
Valentincognito Avatar asked Nov 08 '22 20:11

Valentincognito


1 Answers

I found the solution a couple of days ago, I wanted 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 !

like image 173
Valentincognito Avatar answered Nov 14 '22 22:11

Valentincognito