Joshua Leung
Joshua Leung

Reputation: 2399

How to automatically set language preferences in Laravel each time a user visits?

I want to utilize the localization feature in Laravel for my web app. Here's my pseudocode:

If !session::has(lang)
  Get user's location and set proper language in session
App::setLocale(session::get(lang))

This code may not be perfect, but my main concern is where to put this code so that it will automatically run each time the user visits.

I want to properly centralize the code in one place and don't want to put the code in the wrong place. I could place it in route.php, make a service provide, or utilize a middleware. However, I want to learn the proper practice, any suggestion?

Upvotes: 0

Views: 236

Answers (1)

Chris Pint
Chris Pint

Reputation: 62

I would suggest creating a middleware and then registering it as a global middleware by appending it to the $middleware array in your app/Http/Kernel.php class.

Global middleware is called for every request automatically, so it seems like a good fit for your situation.

Upvotes: 4

Related Questions