Certainly! By default, Laravel loads all JSON translation files for the current locale, which can be inefficient if you have large translation files and only need a subset per page.
Solution: Load Only Required Translations Per Page
Instead of using the default __('...') helper with JSON files, you can:
- Organize translations in PHP files (per feature/page) under
resources/lang/{locale}/. - Load only the needed translations in your controller and pass them to the view (or frontend).
Step 1: Use PHP Translation Files
For example, create resources/lang/en/dashboard.php:
<?php
return [
'welcome' => 'Welcome to your dashboard!',
'stats' => 'Here are your stats.',
];
Step 2: Load Translations in Controller
In your controller, load only the translations needed for the page:
$translations = trans('dashboard');
return view('dashboard', compact('translations'));
Step 3: Use Translations in Blade or JS
In your Blade file:
<h1>{{ $translations['welcome'] }}</h1>
<p>{{ $translations['stats'] }}</p>
Or, if you need them in JavaScript, pass them as JSON:
<script>
window.translations = @json($translations);
</script>
Step 4: For JSON Translations (If You Must)
If you must use JSON files, you can manually parse only the needed file:
$locale = app()->getLocale();
$path = resource_path("lang/{$locale}.json");
$translations = json_decode(file_get_contents($path), true);
// Filter only the keys you need
$neededKeys = ['welcome', 'stats'];
$pageTranslations = array_intersect_key($translations, array_flip($neededKeys));
return view('dashboard', compact('pageTranslations'));
Summary:
Laravel doesn't support partial loading of JSON translation files out of the box. For best performance and maintainability, use PHP translation files organized by feature/page, and load only what you need in your controllers.
Let me know if you need an example for a specific setup (like Inertia, Livewire, or Vue/React)!