I am trying to set up localization on my Laravel Inerita (Vue.js). I know about https://github.com/mcamara/laravel-localization, but this does not support Inertia (at least I was not successful with running this on my Vue.js file) {{ __("text") }} does not work in inertia error: TypeError: _ctx.__ is not a function.
Anyway, I am using a different localization package called laravel-vue-i18n.
I am successful in using this on Vue.js, but I am having problems when setting the locale based on URL. How do I set my routes/middleware to use a nullable locale (en as default)?
File web.php
// Can be nullable locale?
Route::middleware(['setLocale'])->prefix('{locale?}')->group(function () {
Route::resource('posts', PostController::class);
Route::resource('comments', CommentController::class);
});
File SetLocaleMiddleware.php
class SetLocaleMiddleware
{
public function handle($request, Closure $next, $locale = 'en')
{
\Log::info($locale); // Always logs as 'en' even if I add 'ja' in the URL
\Log::info($request->route('locale')); // Locale or whatever is the text after localhost/ for some reason
if (!in_array($locale, ['en', 'ja'])) {
abort(400);
}
App::setLocale($locale);
return $next($request);
}
}
File app/Kernel.php
protected $middlewareAliases = [
'setLocale' => \App\Http\Middleware\SetLocaleMiddleware::class,
];
Expected results:
// Set application language to Japanese
http://localhost/ja
http://localhost/ja/posts
http://localhost/ja/comments
// Set application language to English as default
http://localhost
http://localhost/posts
http://localhost/comments
Note: it does not have to be middleware.
So I found a solution that worked for me, though I am not able to use the
\jain the url route, but instead use laravel'sSessionfacade and update the locale in vue on the fly usingcreateAppnpm install laravel-vue-i18nphp artisan lang:publishi18nVuefromlaravel-vue-i18nin app.ts fileFile app.ts
i18nin vite.config.jsvite.config.js
lang/php_*.jsonin .gitignoreRoute::groupin your web.php. Also include the controller@method to update the locale.File web.php
php artisan make:middleware SetLocaleMiddlewareFile SetLocaleMiddleware.php
php artisan make:controller SetLocaleControllerFile SetLocaleController.php
HandleInertiaRequeststo returnlocaleas propsFile HandleInertiaRequests.php
Bonus, if you are experiencing error 419 (missing csrf token), do the following in your axios (preferably in app.ts/js)
How to use
lang/en/post.php
lang/ja/post.php
any vuejs files
Routes stays as