DEV Community

Ricardo Čerljenko for Lloyds digital

Posted on

Laravel - Serve API requests with translated validation rules

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
Enter fullscreen mode Exit fullscreen mode

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);
    }
}

Enter fullscreen mode Exit fullscreen mode

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
});
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

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.

Also, don’t forget to follow us on Instagram and Facebook!

Top comments (0)