Laravel - How to set lang dynamically for API?

2.2k Views Asked by At

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.

1

There are 1 best solutions below

2
On BEST ANSWER

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