1

I want create a general route to catch the optional lang argument in my laravel 5.2 routes.

Currently I do it with this route

//language switcher
Route::get('lang/{lang}/{suffix}', function($lang, $suffix) {
  Session::set('applocale', $lang);
  return Redirect($suffix);
});

So, if you preceed your url with an optional "/lang/[lang-code]" router will change applocale and redirect to the resource.

However I would like to make in a cleaner way with regular expressions, someting like:

//language switcher
Route::get('(es|ca|en)/{suffix}', function($lang, $suffix) {
  Session::set('applocale', $lang);
  return Redirect($suffix);
});

But don't know how..

1 Answer 1

0

As always say: RTM!

Solution:

// generic language switcher
// catch any route preceded with "es" ,"ca" or "en", set the applocale and 
// redirect to suffix route
Route::get('{lang}/{suffix}', function($lang, $suffix) {
  Session::set('applocale', $lang);
  return Redirect($suffix);
})
->where(['lang' => '(es|ca|en)', 'suffix' => '(.*)']);

https://laravel.com/docs/5.2/routing#parameters-regular-expression-constraints

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.