2

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 );
}
jedrzej.kurylo
  • 39,591
  • 9
  • 98
  • 107
Andrew
  • 189
  • 1
  • 4
  • 18

2 Answers2

2

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

naszy
  • 511
  • 1
  • 7
  • 20
jedrzej.kurylo
  • 39,591
  • 9
  • 98
  • 107
  • it's work, but just another little question, why it save without this line: `Auth::user()->save();` I'm wondered! – Andrew Aug 02 '15 at 12:57
0

Seems that with newest versions of Laravel (im on 5.8) for this middleware to work you need to place it under $middlewareGroups otherwise the call to Auth::user() its always empty.

Following jedrzej-kurylo answer, just move the middleware to:

protected $middlewareGroups = [
        'web' => [
                ...
                'App\Http\Middleware\SetLang',
        ],
];
Kiko Seijo
  • 701
  • 8
  • 11