Search code examples
phplaravellaravel-5laravel-localization

Laravel Set up User Language


I have many controllers and I want to set this code in the all of this(actually all of project), how can i do that?

if( !empty(Input::get('lan')) ){
  Auth::user()->language = Input::get('lan');
  App::setLocale( Auth::user()->language );
}else{
  App::setLocale( Auth::user()->language );
}

Solution

  • You can use Laravel's middleware for that. Middleware is a layer of code that wraps the request processing and can execute additional code before or/and after request is processed.

    First, you need your middleware class. It needs to have one method called handle() that will do the desired logic. In your case it could look like that:

    <?php namespace App\Http\Middleware;
    
    use Auth;
    use App;
    
    class SetLang {
      public function handle($request, Closure $next) {
        if(empty($request->has('lan'))) {
          if (Auth::user()) {
            Auth::user()->language = $request->input('lan');
            Auth::user()->save(); // this will do database UPDATE only when language was changed
          }
          App::setLocale($request->input('lan'));
        } else if (Auth::user()) {
          App::setLocale(Auth::user()->language);
        }
    
        return $next($request);
      }
    }
    

    Then register the middleware in your App\Http\Kernel class so that it gets executed for every request:

    protected $middleware = [
        //here go the other middleware classes
        'App\Http\Middleware\SetLang',
    ];
    

    You can find more info about Middleware in the docs here: http://laravel.com/docs/master/middleware