Support the ongoing development of Laravel.io →
Architecture Requests
Last updated 1 year ago.
0

My REST API accepts a header parameter lang in which the client can tell what language he wants to work in. Straight forward, and stateless.

You could also create an api to ´changelanguage` and keep the language associated with your API Token, but to me that is overkill. I basically have a simple Middleware on my API calls that sets the language from the header. I made the parameter optional with a fallback mechanism though, but it works like a charm.

And since my web front is also consuming the same API using axios, I have an interceptor that adds the client language to all ajax requests to the REST API.

Hope that helps!

0

Thanks for your reply. So if I understood well with a Middleware you read the header and set your response. That means that the request must contains the language chosen, right?

0

the header contains the selected language. I have a fallback in place when the header is not being sent to the server though.

0

Where do you use the middleware to catch the header?In the controller? And what about to use a parameter in the url?Is it so bad?

0

The simplest answer to your quetion is that you have to pass one parameter on api request. in this parameter you have to pass which language user want then on your api request you have to do query using this parameter.or you can pass the value in header.

0

I added the middleware to all my routes (at group level), so that it is one of the first things it does. The middleware is pretty straightforward and compact:

public function handle($request, Closure $next)
  {
    if ($request->header('X-LOCALE')) {
      // Language set in the header of the request should always be primary choice
      App::setLocale($request->header('X-LOCALE'));
    } else {
      // Getting the preferred language from the browser if it matches any of the supported languages
      App::setLocale($request->getPreferredLanguage(config('denja.supported_locales')));
    }
    return $next($request);
  }

You have dozens of ways to implement this, but for us, this works.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

FELPONE felpone Joined 2 Jun 2017

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.