lBestWoW
lBestWoW

Reputation: 31

laravel Localization per user

How do I change the language of each user? For example, some people don't change the language. Some people change the language.

Middleware :

use Closure;
use Auth;

class Localization
  {

   public function handle($request, Closure $next)
    {
     if(\Session::has('locale')) {
       \App::setLocale(\Session::get('locale'));   
      }
     return $next($request);
    }
  }

Upvotes: 1

Views: 2071

Answers (2)

STA
STA

Reputation: 34688

Your method is right, no need to change the middleware. You can put the session on user with controller, like this below way.

Route :

Route::get('/lang',[
    'uses' => 'HomeController@lang',
    'as' => 'lang.index'
]);

Controller :

public function lang(Request $request)
{   
   $user = Auth::user()->id;
   $locale = $request->language;
   App::setLocale($locale);
   session()->put('locale', $locale);
   // if you want to save the locale on your user table, you can do it here
   return redirect()->back();
}

Note : I added the GET method on route, so your URI will be like http://127.0.0.1:8000/lang?language=en, and o controller $request->language will catch the language parameter from your Request. You can modify and use POST method instead

Upvotes: 1

Prasan Ghimire
Prasan Ghimire

Reputation: 194

Save the locale for each user in database. This way you can override app's default locale to user's preferred locale in the middleware.

public function handle($request, Closure $next)
{
 if($user = Auth::user()) {
   App::setLocale($user->locale);   
  }
 return $next($request);
}

If the your application doesn't require user to be authenticated, you can save locale in session for each user when the user change language.

Upvotes: 1

Related Questions