1

I have an endpoint to switch the lang:

{{base_url}}/localize/{lang}

So, The controller

class LocalizationController 
{
 if (!is_null($lang) && !empty($lang)) {
       App::setLocale(request('lang'));
   }
}

But, It seem not working with API. I really appreciated with your help if you have any idea please help me out.

Sok Chanty
  • 1,678
  • 2
  • 12
  • 22

1 Answers1

2

I prefer to use headers for that task. Create new middleware and check it for all requests.

namespace App\Http\Middleware;

use Closure;

class Localization
{
    protected const ALLOWED_LOCALIZATIONS = ['en', 'es', 'ru'];
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $localization = $request->header('Accept-Language');
        $localization = in_array($localization, self::ALLOWED_LOCALIZATIONS, true) ? $localization : 'en';
        app()->setLocale($localization);

        return $next($request);
    }
}

You can choose your own type of localization like en or en_US or whatever. Then just add header to all your requests like: Accept-Language: es

V-K
  • 1,297
  • 10
  • 28
  • Anyways, Is it possible to handle it by create new the endpoint above? – Sok Chanty Oct 05 '20 at 14:17
  • of course, but it's not a good plan. If you do it via the new endpoint, you have to store something like state, to get localization for the next request. But there is no cookie or something like this for API, so you have to store this in db or some file and retrieve every time. It's a bad way and I suggest to use the approach above. – V-K Oct 05 '20 at 14:22