Handling Multilingual APIs in Laravel : Best Practices and Use Case

#Laravel #APIs #Multilingual #Laravel localisation #Laravel Multilingual

4 min read.

Handling Multilingual APIs in Laravel : Best Practices and Use Case
Hamdaoui Wassim Avatar

Hamdaoui Wassim

1
0

In today’s global applications, supporting multiple languages in APIs has become a critical feature. Whether you're building an e-commerce platform or a SaaS product, your backend must be ready to serve content in different languages. In this article, we’ll explore how to handle multilingual APIs in Laravel 12, highlight best practices, and walk through a practical use case.

 

Why API Localization Matters :

Multilingual APIs:

  • Improve user experience for non-English speakers

  • Enable global market expansion

  • Reduce hardcoded translations on the frontend

 

Laravel's Built-in Localization :

Laravel comes with a robust localization system located in the /lang directory. You define translations as PHP or JSON files, and Laravel can automatically serve the correct language based on the Accept-Language header or a custom logic.

Best Practices for Multilingual APIs :

  • Use JSON Language Files
    Prefer JSON files over PHP arrays for API responses for simpler structure and compatibility with JavaScript clients.

  • Detect Language from Request Header or Param
    Use the Accept-Language header or custom query param to set the locale.

  • Keep Translations Centralized
    All messages, labels, and error responses should use translation keys.

  • Fallback Locale
    Always define a fallback locale in config/app.php to prevent missing key issues.

  • Custom Validation Messages
    Use translated validation messages by leveraging Laravel’s lang system.

Implementation Steps :

1. Create JSON Language Files 

resources/lang/en.json
resources/lang/fr.json

en.json

{
    "welcome": "Welcome",
    "email_required": "Email is required"
}

fr.json

{
    "welcome": "Bienvenue",
    "email_required": "L'e-mail est requis"
}

2. Middleware to Set Locale

Create a middleware to detect and set the locale.

php artisan make:middleware SetApiLocale
<?php

// app/Http/Middleware/SetApiLocale.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\App;

class SetApiLocale
{
    public function handle($request, Closure $next)
    {
        $locale = $request->header('Accept-Language', config('app.fallback_locale'));
        App::setLocale(in_array($locale, ['en', 'fr']) ? $locale : config('app.fallback_locale'));

        return $next($request);
    }
}

?>

Register middleware: 

In Laravel 12, global and route middleware are registered inside bootstrap/app.php using the $app instance.

In bootstrap/app.php, find the section where the HTTP kernel is bound (usually at the bottom). Add your middleware to the ->with() method like this:

<?php

use App\Http\Middleware\SetApiLocale;
use Illuminate\Foundation\Bootstrap\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        //  Apply global middleware to all routes
        $middleware->append(SetApiLocale::class);

        // OR register as named route middleware
        $middleware->alias('setLocale', SetApiLocale::class);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

?>

3. Use Translations in Responses :

<?php
 
return response()->json([
    'message' => __('welcome')
]);

?>

Or in validation:

<?php

$request->validate([
    'email' => 'required|email',
], [
    'email.required' => __('email_required')
]);

?>

4. Optional: Support Query Param Locale :

Enhance the middleware to also check for a lang query parameter:

<?php

$locale = $request->query('lang') 
    ?? $request->header('Accept-Language') 
    ?? config('app.fallback_locale');
?>

Use Case: Multilingual Onboarding API :

Endpoint: /api/welcome

Request :

GET /api/welcome
Accept-Language: fr

Response :

{
  "message": "Bienvenue"
}

Fallback example :

GET /api/welcome
Accept-Language: fr

If Spanish isn’t available, Laravel falls back to English:

{
  "message": "Welcome"
}

Testing Your API Localization :

Use tools like Postman or Insomnia:

  • Set Accept-Language: fr in headers.

  • Or test with ?lang=fr in the URL.

 

Multilingual support in APIs is not just a feature—it’s a requirement for scalable and inclusive applications. Laravel 12 makes it easy with its localization system. By following best practices, you ensure that your application is:

  • Maintainable

  • Scalable

  • User-friendly for global audiences

0 Comments