Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel optional prefix routes with regexp

Is there a way to create routes with prefixes so I can have routes like this

/articles.html -> goes to listing  Controller in default language
/en/articles.html -> goes to the same controller
/fr/articles.html -> goes to the same controller

My current problem is that by doing:

Route::group(['prefix=>'/{$lang?}/',function(){});

a route like this: /authors/author-100.html will match a prefix 'authors` , and for sure there is no language called "authors".

I use laravel 5.5

like image 486
user237329 Avatar asked Sep 04 '17 07:09

user237329


People also ask

How do you add a prefix in Laravel?

Route::group(['prefix'=>'admin'],function (){ Route::group(['prefix' => 'admin','middleware' => 'auth'], function () { Route::group(['prefix' => 'candidate','middleware' => 'auth'], function () { Route::get('login', 'frontend\LoginController@login'); Route::get('/home', 'DashboardController@index')->name('home');

What is prefix in Laravel route?

Path prefixes are used when we want to provide a common URL structure. We can specify the prefix for all the routes defined within the group by using the prefix array option in the route group.

Which types of route model binding are supported in Laravel?

Laravel currently supports two types of route model bindings. We have: Implicit model binding. explicit model binding.

How many types of routes are there in Laravel?

Route Parameters Laravel provides two ways of capturing the passed parameter: Required parameter. Optional Parameter.


1 Answers

Another working solution would be to create an array of langs and loop over it:

$langs = ['en', 'fr', ''];

foreach($langs as $lang) {
  Route::get($lang . "/articles", "SomeController@someMethod");
}

For sure this makes your route file less readable, however you may use php artisan route:list to clearly list your routes.

like image 185
Yezan Rafed Avatar answered Oct 15 '22 17:10

Yezan Rafed