Multilingual routes with parameters

1 day ago 4
ARTICLE AD BOX

You missed the dot after the __() call in your route, and that's what causes the syntax error. Take a look:

// Wrong - no dot Route::get('/'. __('routes.community')'/{subcategory}', ...); // The fix Route::get('/'. __('routes.community') . '/{subcategory}', ...);

But honestly, adding the dot won't solve your bigger problem. The __() function only runs once when Laravel builds your routes, so it sticks with whatever language is set by default. Your URLs won't change for different users.

If you want URLs to adjust by language, you'll have to loop through your locales and manually set up each route.

Now you get /en/community/{subcategory} in English and /es/comunidad/{subcategory} in Spanish. To make sure everything else in your app shows up in the user's language, you'll need some middleware that calls app()->setLocale() based on the URL prefix. That way, your app knows which language to use as users move around.

Pankaj's user avatar

From what I know about laravel, it registers routes once at boot and doesn’t dynamically switch route paths per request. So if you do:

__('routes.community') = "community"

then only /community/{subcategory} will exists.

If you switch locale later, laravel won’t magically create /comunidad/...

So use locala prefix instead, do something like:

Route::group(['prefix' => app()->getLocale()], function () { Route::get(__('routes.community') . '/{subcategory}', [SubCategoryFreeController::class, 'index']) ->name('subcategoryfree'); });

Anayo Samson Oleru's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article