DEV Community

Ricardo Čerljenko for Lloyds digital

Posted on

7

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!

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay