We can easily do Laravel rest api localization with the help of middleware,
with the help of API translation, we can translate all API responses into different international
languages.
1 - Creating Language Middleware
For example:
We will create ApiLocalization Middleware.
Run the Artisan command to generate the middle.
php artisan make:middleware ApiLocalization
After running the above command in Laravel Artisan a new middleware will be created under
path: your_project_folder\app\http\middleware.
We need to update the ApiLocalization middleware which will check the
X-localization in the request.
$local = ($request->hasHeader('X-localization')) ? $request->header('X-localization') : 'en';
After checking the required header in the request, it will then set the local
app()->setLocale($local);
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgroNBnG1Y-GAPWNg02QTo7zw2VriqJPDDZ1exMHpk9tR6Y78inw6P9bAo2KZsv7YXtUjIf5AJcfH01xh8-DiibzMXRX2ljGwBEelsvxCMydrDk04LCc-ib3OHTA6LnxVNumtaF2yU7cDg/w496-h274/image.png)
This is how we can switch between different languages in laravel using middleware.
We need to update the ApiLocalization middleware which will check the
X-localization in the request.
$local = ($request->hasHeader('X-localization')) ? $request->header('X-localization') : 'en';
After checking the required header in the request, it will then set the local
app()->setLocale($local);
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgroNBnG1Y-GAPWNg02QTo7zw2VriqJPDDZ1exMHpk9tR6Y78inw6P9bAo2KZsv7YXtUjIf5AJcfH01xh8-DiibzMXRX2ljGwBEelsvxCMydrDk04LCc-ib3OHTA6LnxVNumtaF2yU7cDg/w496-h274/image.png)
This is how we can switch between different languages in laravel using middleware.
No comments:
Post a Comment