0

I have a project in laravel 11 and there are some issues with my config.

The site should support optional locale param to differentiate between default and custom language:

DE: https://example.com/auto/1/my-ferrari
EN: https://example.com/en/auto/1/my-ferrari

This is the code defined in routes:

Route::get('/auto/{id}/{slug}', [ItemController::class, 'show'])->name('items.show.default');

Route::group([
  'prefix' => '{locale}', 
  'middleware' => ['setLocale'],
  'where' => ['locale' => 'de|en',
  'as' => 'localized.'
], function () {
  Route::get('/auto/{id}/{slug}', [ItemController::class, 'show'])->name('items.show.default');
});

SetLocale middleware just sets the App and Session locale.

The controller looks like this:

public function show(Request $request, $id, $slug)
{
    dd('$id: '.$id);
    $item = Item::where('id', $id)->firstOrFail();
}

The issue is that $id in the controller method wrongly shows the value.

https://example.com/auto/1/my-ferrari       $id: 1
https://example.com/en/auto/1/my-ferrari    $id: en

Question is: Is there any laravel default function or recommended way to handle this challenge?

Thanks!

4
  • 1
    That's how it's always worked; chained URL Params are not the right solution when one of them is optional, since (as you're seeing), omitting an optional one messes with the rest of them and causes them to be out of order. The solution is make locale required or omit it completely and use something else, like a Session variable or similar. Commented Mar 31 at 14:34
  • That is the solution for either an international (domain.com) or a small project. In my case, it is for a local and big brand where having example.de/de... is not an option. Commented Apr 1 at 19:47
  • Then omit it; detect the current language of the browser and store that, then allow the user to change their language manually. None of the localized websites I've worked on have used /{lang} in the URL; big, small, local and international 🤷‍♂️ Commented Apr 1 at 19:54
  • That means those websites either used entirely unique URLs without {lang} or the client wasn't concerned about SEO. For this project, the {lang} parameter alone will determine the URL variation. Commented Apr 1 at 20:08

1 Answer 1

0

I’ve come across two potential solutions, but I am unsure if they are the recommended ones:

  • Removing locale variable in the middleware, like $request->route()->forgetParameter('locale')

  • Ignoring the params defined in controller methods and instead use route params, like $request->route('id')

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.