How to Build Multilingual Laravel Pages with Localized URLs and Translated Models

Build multilingual Laravel pages with locale-safe URLs, Eloquent content translations, localized slugs, predictable fallbacks, and language links.

Laravel Published
On this page

An Arabic visitor opens a product page. The URL is Arabic, the navigation is Arabic, but the product title is English. Then they click the language switcher, which preserves the Arabic product slug in an English URL and returns a 404. Meanwhile, an API consumer sends Accept-Language: ar and receives a cached English response.

All three failures can occur in an application that already uses Laravel's translation files correctly. Choosing a request language, translating database content, and identifying a resource by a translated URL are separate problems. Treating them as one switch is where multilingual applications become unreliable.

This guide builds a small English/Arabic product catalogue. We start with Laravel itself, preserve its useful primitives, then connect Pharaonic Laravel Localization and Pharaonic Laravel Translatable at the boundaries where they replace repeated application-specific logic.

Quick Answer / TL;DR: Use Laravel's app.locale for the active language, app.fallback_locale for missing display text, and lang/ files for interface strings. A localized website also needs URL routing and locale-aware model lookup; database content needs explicit per-locale storage. The two Pharaonic packages address those different concerns, but the model must explicitly connect translated slugs to localized route binding.

#Define the Language Contract Before Writing Routes

Our catalogue needs two web URLs for a product, a stable API URL, and a deliberate rule for missing translations.

Concern English Arabic Owner
Website index /products /ar/المنتجات Localized routing
Product URL /products/light-lens /ar/المنتجات/عدسة-خفيفة Routing + translated slug
Product name Light Lens عدسة خفيفة Eloquent content
Interface label Add to cart أضف إلى السلة Laravel language files
API index /api/products Same URL, negotiated response HTTP locale selection

The unprefixed URL is always English in this design. A visitor's cookie or browser setting must not silently change /products to Arabic: that URL has one canonical language. An API response can vary by Accept-Language because its URL intentionally does not encode a locale.

Also distinguish two forms of fallback. A missing product name may reasonably display the English name. A missing Arabic slug must not silently generate a supposedly Arabic URL containing the English slug. Content fallback and URL identity have different correctness requirements.

#Build the Native Laravel Baseline

Laravel already solves interface text and per-request application locale. In .env, set:

1APP_LOCALE=en
2APP_FALLBACK_LOCALE=en

Create ordinary lang/en/catalog.php and lang/ar/catalog.php files (run php artisan lang:publish first if your application has no lang/ directory):

1<?php
2 
3// lang/en/catalog.php
4return ['add_to_cart' => 'Add to cart'];
1<?php
2 
3// lang/ar/catalog.php
4return ['add_to_cart' => 'أضف إلى السلة'];

Blade can now render {{ __('catalog.add_to_cart') }} in the active locale. Laravel also lets you call App::setLocale('ar') during a request. Neither feature stores an Arabic product name or creates /ar/المنتجات automatically. These are separate jobs; see the Laravel localization documentation.

#Native database translations

A normal Eloquent design can use a products table and a product_translations table keyed by (product_id, locale):

1<?php
2 
3// database/migrations/xxxx_xx_xx_create_catalogue_tables.php
4use Illuminate\Database\Migrations\Migration;
5use Illuminate\Database\Schema\Blueprint;
6use Illuminate\Support\Facades\Schema;
7 
8return new class extends Migration {
9 public function up(): void
10 {
11 Schema::create('products', function (Blueprint $table) {
12 $table->id();
13 $table->boolean('is_published')->default(false);
14 $table->timestamps();
15 });
16 
17 Schema::create('product_translations', function (Blueprint $table) {
18 $table->id();
19 $table->foreignId('product_id')->constrained()->cascadeOnDelete();
20 $table->string('locale', 35);
21 $table->string('name')->nullable();
22 $table->string('slug')->nullable();
23 $table->text('description')->nullable();
24 $table->timestamps();
25 $table->unique(['product_id', 'locale']);
26 $table->unique(['locale', 'slug']);
27 });
28 }
29 
30 public function down(): void
31 {
32 Schema::dropIfExists('product_translations');
33 Schema::dropIfExists('products');
34 }
35};

The first unique index prevents duplicate translations for a product and locale. The second prevents two products from claiming the same slug in one locale. Both translated fields are nullable so partially translated records can exist; later, the model marks fields as required for editorial completeness, not as database NOT NULL constraints. It assumes slugs are unique within the entire catalogue; tenant-scoped applications should put their tenant identity into the uniqueness model as well.

1<?php
2 
3// app/Models/Product.php: native baseline only
4namespace App\Models;
5 
6use Illuminate\Database\Eloquent\Model;
7use Illuminate\Database\Eloquent\Relations\HasMany;
8 
9class Product extends Model
10{
11 protected $fillable = ['is_published'];
12 
13 public function translations(): HasMany
14 {
15 return $this->hasMany(ProductTranslation::class);
16 }
17}
1<?php
2 
3// app/Models/ProductTranslation.php
4namespace App\Models;
5 
6use Illuminate\Database\Eloquent\Model;
7 
8class ProductTranslation extends Model
9{
10 protected $fillable = ['product_id', 'locale', 'name', 'slug', 'description'];
11}

A controller can query the requested translation and then try the fallback locale:

1<?php
2 
3use App\Models\Product;
4 
5$product = Product::findOrFail($id);
6$requested = app()->getLocale();
7 
8$translation = $product->translations()->where('locale', $requested)->first();
9$fallback = $requested === config('app.fallback_locale')
10 ? null
11 : $product->translations()->where('locale', config('app.fallback_locale'))->first();
12 
13$name = $translation?->name ?? $fallback?->name;

This is legitimate Eloquent, not a defective workaround. For two languages and a few pages, you can stop here. But every controller now has to settle missing values, eager-loading, translated slugs, strict URL lookup, language-switch links, and index queries. The native solution becomes costly when the same rules have to be repeated consistently, not merely because the application supports multiple languages.

#Connect URL Localization to Eloquent Translation

The package implementation replaces the native model logic while retaining the same table layout:

1composer require pharaonic/laravel-localization pharaonic/laravel-translatable
2php artisan vendor:publish --tag=localization-config
3php artisan vendor:publish --tag=translatable-config

In the published config/pharaonic/localization.php, change supported to ['en', 'ar']; keep the provided path and resolvers defaults. The important settings are:

1<?php
2 
3// Relevant entries in config/pharaonic/localization.php
4return [
5 'supported' => ['en', 'ar'],
6 'path' => [
7 'hide_default' => true,
8 'canonical_redirect' => true,
9 'prefixes' => [],
10 ],
11 'resolvers' => [
12 'web' => ['user', 'session', 'cookie', 'header'],
13 'api' => ['user', 'header'],
14 ],
15 'session' => ['key' => 'locale'],
16 'cookie' => [
17 'key' => 'locale',
18 'minutes' => 60 * 24 * 365,
19 'same_site' => 'lax',
20 'secure' => null,
21 ],
22 'header' => ['name' => 'Accept-Language'],
23 'locales' => [],
24];

The default and fallback locale still come from Laravel, not duplicate configuration keys. In config/translatable.php, the default strategy is env('TRANSLATABLE_STRATEGY', 'table'). We use the default table strategy for product content because it suits several locales and ordinary relational constraints.

#Keep URL segments separate from model slugs

The string products is part of the route; the slug identifies one product. Translate the former with a language file, not an Eloquent field:

1<?php
2 
3// lang/ar/routes.php
4return ['products' => 'المنتجات'];
1<?php
2 
3// routes/web.php
4use App\Http\Controllers\ProductController;
5use Illuminate\Support\Facades\Route;
6 
7Route::localized(function (): void {
8 Route::get('/products', [ProductController::class, 'index'])
9 ->name('products.index');
10 
11 Route::get('/products/{product}', [ProductController::class, 'show'])
12 ->name('products.show');
13});

This registers real routes in both languages: /products/{product} and /ar/المنتجات/{product}. With the default-prefix policy above, GET /en/products redirects to /products; it does not negotiate a different language. Unlike runtime route rewriting, the registration is compatible with route:cache when the actions use controllers. A change to supported locales or translated segments requires a route-cache rebuild.

#Make translated fields the model's content API

Replace the native Product model shown earlier with the following table-strategy implementation. Keep ProductTranslation and the migration as written above:

1<?php
2 
3// app/Models/Product.php: package implementation
4namespace App\Models;
5 
6use Illuminate\Database\Eloquent\Builder;
7use Illuminate\Database\Eloquent\Model;
8use Pharaonic\Laravel\Localization\Contracts\HasLocalizedRouteKey;
9use Pharaonic\Laravel\Translatable\Contracts\TableTranslatable;
10use Pharaonic\Laravel\Translatable\Translatable;
11 
12class Product extends Model implements TableTranslatable, HasLocalizedRouteKey
13{
14 use Translatable;
15 
16 protected $fillable = ['is_published'];
17 
18 public function translatable(): array
19 {
20 return [
21 'name' => ['type' => 'string', 'required' => true],
22 'slug' => ['type' => 'string', 'required' => true, 'fallback' => false],
23 'description' => ['type' => 'string'],
24 ];
25 }
26 
27 public function getLocalizedRouteKey(string $locale): ?string
28 {
29 $slug = $this->getTranslation('slug', $locale);
30 
31 return $slug === null || trim($slug) === '' ? null : $slug;
32 }
33 
34 public function scopeWithLocalizedUrl(Builder $query, string $locale): void
35 {
36 $query->whereHas('translations', function (Builder $translations) use ($locale): void {
37 $translations->where('locale', $locale)
38 ->whereNotNull('slug')
39 ->whereRaw('TRIM(slug) <> ?', ['']);
40 });
41 }
42 
43 public function resolveRouteBinding($value, $field = null)
44 {
45 if (locale()->mode() !== 'path') {
46 // Keep normal ID/key binding for non-localized API and other routes.
47 return parent::resolveRouteBinding($value, $field);
48 }
49 
50 return $this->newQuery()
51 ->whereTranslation('slug', (string) $value, app()->getLocale())
52 ->first();
53 }
54}

That last method is application integration code, not an automatic feature supplied by either package. laravel-localization sets the route locale before Laravel substitutes route parameters; laravel-translatable exposes the exact localized slug and a locale-aware query. The model combines them. The explicit mode() !== 'path' branch matters: without it, overriding binding to look up slugs could accidentally break API routes that still identify products by ID.

Renamed slugs need a separate slug-history/redirect policy. Cross-language matches would weaken the URL contract.

withLocalizedUrl() excludes null, empty, and space-only slugs before pagination. getLocalizedRouteKey() also rejects blank values when building language links. Validate all new slugs at the write boundary, as shown below; these guards also handle existing blank records.

A controller and two small views complete the web example:

1<?php
2 
3// app/Http/Controllers/ProductController.php
4namespace App\Http\Controllers;
5 
6use App\Models\Product;
7use Illuminate\View\View;
8 
9class ProductController extends Controller
10{
11 public function index(): View
12 {
13 $products = Product::query()
14 ->where('is_published', true)
15 ->withLocalizedUrl(app()->getLocale())
16 ->withTranslations([app()->getLocale(), config('app.fallback_locale')])
17 ->paginate(20);
18 
19 return view('products.index', compact('products'));
20 }
21 
22 public function show(Product $product): View
23 {
24 abort_unless($product->is_published, 404);
25 
26 return view('products.show', compact('product'));
27 }
28}
1<!-- resources/views/products/index.blade.php -->
2@foreach ($products as $product)
3 <a href="{{ locale()->route('products.show', ['product' => $product]) }}">
4 {{ $product->name }}
5 </a>
6@endforeach
7{{ $products->links() }}
1<!-- resources/views/products/show.blade.php -->
2<!doctype html>
3<html lang="{{ locale()->normalize(locale()->current()) }}" dir="{{ locale()->direction() }}">
4<head>
5 <link rel="canonical" href="{{ locale()->alternates()[locale()->current()] ?? url()->current() }}">
6 @foreach (locale()->hreflangs() as $language => $url)
7 <link rel="alternate" hreflang="{{ $language }}" href="{{ $url }}">
8 @endforeach
9</head>
10<body>
11 <h1>{{ $product->name }}</h1>
12 <p>{{ $product->description }}</p>
13</body>
14</html>

The show view owns canonical and alternate tags here. In a larger application, move that head block into the shared layout or pass its URL map to your SEO layer.

#Save values once, then let the current locale select them

1<?php
2 
3use App\Models\Product;
4use Illuminate\Support\Facades\Validator;
5 
6$translations = [
7 'en' => [
8 'name' => 'Light Lens',
9 'slug' => 'light-lens',
10 'description' => 'A compact travel lens.',
11 ],
12 'ar' => [
13 'name' => 'عدسة خفيفة',
14 'slug' => 'عدسة-خفيفة',
15 'description' => 'عدسة صغيرة للسفر.',
16 ],
17];
18 
19foreach ($translations as &$translation) {
20 $slug = $translation['slug'] ?? null;
21 if (is_string($slug)) {
22 $translation['slug'] = trim($slug) === '' ? null : trim($slug);
23 }
24}
25unset($translation);
26 
27Validator::make($translations, [
28 '*.slug' => ['nullable', 'string', 'max:255', 'regex:/\A[\p{L}\p{M}\p{N}]+(?:-[\p{L}\p{M}\p{N}]+)*\z/u'],
29])->validate();
30 
31$product = Product::create(['is_published' => true]);
32$product->fillTranslations($translations)->save();
33 
34$product->getTranslation('name', 'ar'); // 'عدسة خفيفة'
35$product->getTranslation('slug', 'en'); // 'light-lens'

Normalize blank slugs to null and validate their format on every write path, including imports and admin forms. This rule allows Unicode letters, combining marks, numbers, and separating hyphens; the database index enforces per-locale uniqueness. A partial translation may omit its slug.

In a view, $product->name reads the current request locale, with display fallback. getTranslation('name', 'ar') reads the exact stored value.

To inspect what users actually see rather than guessing which locale supplied it:

1<?php
2 
3$resolved = $product->resolveTranslation('name', 'ar');
4 
5$resolved->value; // Displayed value.
6$resolved->resolvedLocale; // Locale that supplied that value.
7$resolved->isFallback; // Whether a fallback was used.
8$product->missingTranslations('ar'); // Required fields still missing.

hasCompleteTranslation('ar') checks the fields marked required; it does not validate URL syntax or require every optional field to be translated.

For this product, the logical route name is products.show in both languages. Let Localization choose the concrete route and ask the model for its locale-specific key:

1<?php
2 
3locale()->route('products.show', ['product' => $product], 'en');
4// https://example.com/products/light-lens
5 
6locale()->route('products.show', ['product' => $product], 'ar');
7// https://example.com/ar/المنتجات/عدسة-خفيفة (URL-encoded on the wire)

For the current page, switchUrl() preserves route parameters and the query string; alternates() returns query-free variants; hreflangs() also adds x-default for the default-locale URL.

1<!-- resources/views/partials/language-switcher.blade.php -->
2<nav aria-label="Language">
3 @foreach (locale()->supported() as $code)
4 @if ($url = locale()->switchUrl($code))
5 <a href="{{ $url }}"
6 lang="{{ locale()->normalize($code) }}"
7 hreflang="{{ locale()->normalize($code) }}"
8 @if ($code === locale()->current()) aria-current="true" @endif>
9 {{ locale()->nativeName($code) }}
10 </a>
11 @endif
12 @endforeach
13</nav>

If a product has no usable Arabic slug, switchUrl('ar') returns null and alternates() omits Arabic. The switcher and the head tags therefore advertise only available variants.

There is no automatic remembered-language redirect on a path-localized website. To store a preference after a deliberate language choice, use locale()->remember($code, 'session') or remember($code, 'cookie') from an application-owned, CSRF-protected route. Then redirect to a URL generated for the chosen locale. A saved preference never overrides an explicit /ar/... URL.

#Keep APIs on a Negotiated Locale Contract

The API keeps one URL per resource. Ensure routes/api.php is registered through withRouting(api: ...) in bootstrap/app.php; use Laravel's php artisan install:api if you also need its Sanctum setup. The localization middleware uses the api resolver profile, initially ['user', 'header'], without redirecting:

1<?php
2 
3// routes/api.php
4use App\Http\Controllers\ApiProductController;
5use Illuminate\Support\Facades\Route;
6 
7Route::middleware('localization')->group(function (): void {
8 Route::get('/products', [ApiProductController::class, 'index']);
9 Route::get('/products/{product}', [ApiProductController::class, 'show']);
10});
1<?php
2 
3// app/Http/Controllers/ApiProductController.php
4namespace App\Http\Controllers;
5 
6use App\Models\Product;
7use Illuminate\Http\JsonResponse;
8 
9class ApiProductController extends Controller
10{
11 public function index(): JsonResponse
12 {
13 $products = Product::query()
14 ->where('is_published', true)
15 ->withTranslations([app()->getLocale(), config('app.fallback_locale')])
16 ->orderBy('id')
17 ->paginate(20)
18 ->through(fn (Product $product) => $this->productData($product));
19 
20 return response()->json($products);
21 }
22 
23 public function show(Product $product): JsonResponse
24 {
25 abort_unless($product->is_published, 404);
26 $product->load('translations');
27 
28 return response()->json($this->productData($product));
29 }
30 
31 private function productData(Product $product): array
32 {
33 return [
34 'id' => $product->getKey(),
35 'name' => $product->name,
36 'name_locale' => $product->resolveTranslation('name')->resolvedLocale,
37 ];
38 }
39}

The index returns a paginator with products in data and pagination metadata alongside it. Both endpoints hide unpublished products; the detail endpoint binds {product} by ID.

With Accept-Language: ar-EG,ar;q=0.9,en;q=0.8 and no higher-priority user preference, ar is selected from the supported list. The middleware emits Content-Language, adds Vary: Accept-Language when the header resolver was read, and marks relevant user/session/cookie-selected cacheable responses private. Your own custom resolver must also set appropriate cache headers if it reads tenant or personal data. Avoid public full-response caching across languages unless the cache key explicitly distinguishes the relevant locale and variation policy.

For authenticated users, the built-in user resolver reads preferredLocale() from a model implementing Laravel's HasLocalePreference; it does not infer a column magically. An API that authenticates tokens should put authentication middleware before localization, for example ['auth:sanctum', 'localization'] when Sanctum is actually installed. Sessions and encrypted cookies belong in a web middleware context, not a default stateless API context.

#Choose Translation Storage by Query Shape

The example used the default table strategy, not because it is universally faster, but because translated slugs benefit from an ordinary (locale, slug) unique index and because content may grow to more locales. Translatable exposes three explicit strategies with a shared model API:

Strategy Storage shape Useful when Trade-off
table product_translations rows Many locales, full-text content, ordinary relational constraints Extra relation; eager-load it for lists
json products.name JSON object by locale Few translated fields, variable locale set Queries/indexes are database-specific in cost and design
columns name_en, name_ar Small, fixed locale set and ordinary column indexes Adding a locale requires a schema migration

A model can explicitly implement one marker interface: TableTranslatable, JsonTranslatable, or ColumnsTranslatable. Without a marker it inherits translatable.strategy (default: table). The default is application-wide, but the marker makes an individual model's choice explicit. There are no shared-table, hybrid, or per-field storage strategies in this API.

For example, an independently managed tag with a JSON column named name might implement JsonTranslatable, while a fixed-locale lookup table could implement ColumnsTranslatable. Do not change a model's strategy without moving the data. The supported workflow is translatable:inspect, translatable:make-schema, translatable:migrate (dry-run first), translatable:verify, then switching the marker. Use a real migration review and backup before applying it.

#Query and loading consequences

A product index in the active locale should eager-load the table translations instead of reading them lazily per row:

1<?php
2 
3$products = Product::query()
4 ->where('is_published', true)
5 ->withLocalizedUrl(app()->getLocale())
6 ->withTranslations([app()->getLocale(), config('app.fallback_locale')])
7 ->orderByTranslation('name', 'asc', app()->getLocale())
8 ->paginate(20);
9 
10$untranslated = Product::query()
11 ->whereMissingTranslation('ar', 'name')
12 ->get();

The same translation query API works across the three strategies, but SQL and indexing costs differ. Check query plans on your database, especially for large catalogues and fallback sorting. withLocalizedUrl() is an application scope specific to this guide's table strategy.

#Test the Invariants That Usually Break

These feature tests use the migration, package model, controllers, registered web/API routes, and views above. Keep APP_LOCALE=en and APP_FALLBACK_LOCALE=en in the test environment, with supported set to ['en', 'ar'] before application boot.

1<?php
2 
3// tests/Feature/MultilingualCatalogueTest.php
4namespace Tests\Feature;
5 
6use App\Models\Product;
7use Illuminate\Foundation\Testing\RefreshDatabase;
8use Tests\TestCase;
9 
10class MultilingualCatalogueTest extends TestCase
11{
12 use RefreshDatabase;
13 
14 private function product(array $arabic = [], bool $published = true): Product
15 {
16 $product = Product::create(['is_published' => $published]);
17 $product->fillTranslations([
18 'en' => ['name' => 'Light Lens', 'slug' => 'light-lens'],
19 'ar' => $arabic,
20 ])->save();
21 
22 return $product;
23 }
24 
25 public function test_arabic_url_resolves_only_the_arabic_slug(): void
26 {
27 $product = $this->product(['name' => 'عدسة خفيفة', 'slug' => 'عدسة-خفيفة']);
28 
29 $this->get(locale()->route('products.show', ['product' => $product], 'ar'))
30 ->assertOk()
31 ->assertSee('عدسة خفيفة');
32 
33 $this->get('/ar/المنتجات/light-lens')->assertNotFound();
34 }
35 
36 public function test_missing_arabic_slug_is_not_a_language_alternate(): void
37 {
38 $this->product(['name' => 'عدسة خفيفة']);
39 
40 $this->get('/products/light-lens')
41 ->assertOk()
42 ->assertSee('rel="canonical"', false)
43 ->assertDontSee('hreflang="ar"', false);
44 
45 $this->get('/ar/المنتجات')->assertOk()->assertDontSee('عدسة خفيفة');
46 }
47 
48 public function test_blank_slugs_are_excluded_from_lists_and_alternates(): void
49 {
50 // Deliberately bypass input validation to simulate legacy records.
51 foreach (['', ' '] as $slug) {
52 $product = $this->product(['name' => 'Blank slug product', 'slug' => $slug]);
53 
54 $this->get('/ar/المنتجات')
55 ->assertOk()
56 ->assertDontSee('Blank slug product');
57 
58 $this->get('/products/light-lens')
59 ->assertOk()
60 ->assertDontSee('hreflang="ar"', false);
61 
62 $product->delete();
63 }
64 }
65 
66 public function test_display_name_falls_back_without_changing_the_slug(): void
67 {
68 $product = $this->product(['slug' => 'عدسة-خفيفة']);
69 $resolved = $product->resolveTranslation('name', 'ar');
70 
71 $this->assertSame('Light Lens', $resolved->value);
72 $this->assertSame('en', $resolved->resolvedLocale);
73 $this->assertTrue($resolved->isFallback);
74 $this->assertNull($product->getTranslation('name', 'ar'));
75 
76 $this->get('/ar/المنتجات/عدسة-خفيفة')
77 ->assertOk()
78 ->assertHeader('Content-Language', 'ar')
79 ->assertSee('Light Lens');
80 }
81 
82 public function test_arabic_cookie_does_not_change_an_unprefixed_page(): void
83 {
84 $this->product(['name' => 'عدسة خفيفة', 'slug' => 'عدسة-خفيفة']);
85 
86 $this->withCookie('locale', 'ar')->get('/products')
87 ->assertOk()
88 ->assertHeader('Content-Language', 'en')
89 ->assertSee('Light Lens')
90 ->assertDontSee('عدسة خفيفة');
91 }
92 
93 public function test_default_prefix_redirects_to_the_canonical_url(): void
94 {
95 $this->get('/en/products')->assertStatus(301)->assertRedirect('/products');
96 }
97 
98 public function test_api_negotiates_language_and_declares_cache_variation(): void
99 {
100 $this->product(['name' => 'عدسة خفيفة']);
101 
102 $response = $this->withHeaders(['Accept-Language' => 'ar-EG,ar;q=0.9'])
103 ->getJson('/api/products')
104 ->assertOk()
105 ->assertHeader('Content-Language', 'ar')
106 ->assertJsonPath('data.0.name', 'عدسة خفيفة')
107 ->assertJsonPath('data.0.name_locale', 'ar');
108 
109 $this->assertContains('Accept-Language', $response->baseResponse->getVary());
110 $this->assertTrue($response->baseResponse->headers->hasCacheControlDirective('private'));
111 }
112 
113 public function test_api_keeps_id_binding_and_reports_display_fallback(): void
114 {
115 $product = $this->product();
116 
117 $this->withHeaders(['Accept-Language' => 'ar'])
118 ->getJson('/api/products/'.$product->getKey())
119 ->assertOk()
120 ->assertJsonPath('id', $product->getKey())
121 ->assertJsonPath('name', 'Light Lens')
122 ->assertJsonPath('name_locale', 'en');
123 
124 $this->getJson('/api/products/light-lens')->assertNotFound();
125 }
126 
127 public function test_unpublished_products_are_hidden_on_web_and_api(): void
128 {
129 $product = $this->product(['name' => 'عدسة خفيفة', 'slug' => 'عدسة-خفيفة'], false);
130 
131 $this->get('/products')->assertOk()->assertDontSee('Light Lens');
132 $this->get('/products/light-lens')->assertNotFound();
133 $this->get('/ar/المنتجات/عدسة-خفيفة')->assertNotFound();
134 $this->getJson('/api/products')->assertOk()->assertJsonCount(0, 'data');
135 $this->getJson('/api/products/'.$product->getKey())->assertNotFound();
136 }
137 
138 public function test_api_paginates_published_products(): void
139 {
140 for ($index = 1; $index <= 21; $index++) {
141 $product = Product::create(['is_published' => true]);
142 $product->setTranslation('name', 'en', 'Lens '.$index)->save();
143 }
144 
145 $this->getJson('/api/products')->assertOk()
146 ->assertJsonCount(20, 'data')
147 ->assertJsonPath('total', 21)
148 ->assertJsonPath('last_page', 2);
149 
150 $this->getJson('/api/products?page=2')->assertOk()
151 ->assertJsonCount(1, 'data')
152 ->assertJsonPath('current_page', 2);
153 }
154}

Run the suite, then rebuild the route cache and run it again to check route registration as well as request behavior:

1php artisan test --filter=MultilingualCatalogueTest
2php artisan route:cache
3php artisan test --filter=MultilingualCatalogueTest
4php artisan route:clear

These checks cover the default private JSON responses. If your application enables shared caching or adds custom resolvers, also test its public-to-private transitions and cache keys with authenticated user preferences.

#When You Do Not Need Both Packages

If you only translate navigation, validation messages, and static copy, Laravel's lang/ files are enough. If users switch a simple internal dashboard between two languages, a small middleware that calls App::setLocale() may be all you need. If you only translate model fields in a single-language URL scheme, a storage strategy or a simple Eloquent relationship may be enough without specialized routing.

Use both packages when public URLs carry a stable language, products have independently translated content and slugs, and the same locale and fallback rules must remain consistent across controllers, SEO links, and API responses. They still do not provide a translation editor, machine translation, a slug-history service, or an automatic integration between the two packages. Those belong to your application if your product needs them.

The useful architecture is not "install localization twice." It is one authoritative locale for the current request, one explicit place to store each translated field, and a strict distinction between content that may fall back and URLs that must identify exactly one localized resource.

#References