Ricardo Čerljenko
Posted on October 19, 2022
Consider building a mobile app (or a website) which connects to a Laravel CMS over API for dynamic content. Now, the app can be a multi-language app which expects to receive a translated content from the CMS.
Usually, in our company, we instruct our frontend developers to send a lang
query param on every request in order to deliver the correct translated content back.
E.g.:
GET /api/blogs?lang=en
However, Laravel validation is not aware of this and it always returns validation error messages according to app locale (or fallback locale).
Therefore we created a route middleware which groups all API routes and sets app locale based on the lang
query param:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class ChangeLocale
{
/**
* Handle an incoming request.
*/
public function handle(Request $request, Closure $next): Response
{
$locale = $request->query('lang');
if ($locale) {
app()->setLocale($locale);
}
return $next($request);
}
}
And in routes file:
// routes/api.php
use App\Http\Middleware\ChangeLocale;
use Illuminate\Support\Facades\Route;
Route::middleware(ChangeLocale::class)->group(function (): void {
// ROUTES
});
Now your validation messages will be in the requested locale. If you don't like handling this over query param you can always use a header or something else, e.g.:
$locale = $request->header('Accept-Language');
Thank you for reading this! If you've found this interesting, consider leaving a ❤️, 🦄 , and of course, share and comment on your thoughts!
Lloyds is available for partnerships and open for new projects. If you want to know more about us, check us out.
Posted on October 19, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 28, 2024