Kalanj Djordje Djordje
Kalanj Djordje Djordje

Reputation: 1352

Laravel how to add group prefix parameter to route function

For example, I have defined routes like this:

$locale = Request::segment(1);

Route::group(array('prefix' => $locale), function()
{
  Route::get('/about', ['as' => 'about', 'uses' => 'aboutController@index']);
}

I want to generate links for several locales (en, de, es,...). When I try to provide prefix parameter like this

$link = route('about',['prefix' => 'de']);

I got link like this example.com/en/about?prefix=de How to provide prefix param to got link like this example.com/de/about

Upvotes: 9

Views: 29439

Answers (5)

Mohit Nandpal
Mohit Nandpal

Reputation: 143

you can use the prefix method within a Route group to define a common prefix for a group of routes.

Route::group(['prefix' => 'admin'], function () {
    // Your admin routes here
    Route::get('dashboard', 'AdminController@dashboard');
    Route::get('users', 'AdminController@users');
    // ...
});

In the above example, all routes defined within the Route::group will have the "/admin" prefix.

Official Documentation: https://laravel.com/docs/10.x/routing#route-groups

Upvotes: 0

lagbox
lagbox

Reputation: 50551

You can play around with something like this perhaps.

Route::group(['prefix' => '{locale}'], function () {
    Route::get('about', ['as' => 'about', 'uses' => '....']);
});

route('about', 'en');  // http://yoursite/en/about
route('about', 'de');  // http://yoursite/de/about

Upvotes: 14

Vikas
Vikas

Reputation: 993

Try this:

$locale = Request::segment(1);

Route::group(array('prefix' => $locale), function()
{
    Route::get('/about', ['as' => 'about', 'uses' => 'aboutController@index']);
}

And while providing a link, you can use url helper function instead of route:

$link = url('de/about');

If you want more generic, use this in controller/view:

 $link = url($locale.'/about');

where $locale could be en,de,etc

Upvotes: 1

Kiran Subedi
Kiran Subedi

Reputation: 2284

You can do like this :

Route::group(['prefix'=>'de'],function(){
    Route::get('/about', [
       'as' => 'about',
       'uses' => 'aboutController@index'
    ]);

});

Now route('about') will give link like this : example.com/de/about

Upvotes: 0

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21422

You can simply achieve it like as

Route::group(['prefix' => 'de'], function () {
    Route::get('about', ['as' => 'de.about', 'uses' => 'aboutController@index']);
});

And you can use it like as

$link = route('de.about');

Upvotes: -1

Related Questions