Иван
Иван

Reputation: 97

Setting aliases for a route in Laravel

I have a few identical pages which have different urls. How can I set for a route these aliases? So far, I only see the following method:

Route::get('/alias1', 'HomeController@someAction');
Route::get('/alias1.html', 'HomeController@someAction');
Route::get('/alias1.php', 'HomeController@someAction');
Route::get('/alias4', 'HomeController@someAction');

Is there a prettier way to set aliases?

Upvotes: 2

Views: 10444

Answers (3)

Vishal Tarkar
Vishal Tarkar

Reputation: 826

Your Route :

Route::get('/{slug}', 'HomeController@someAction');

Your Controller function:

function someAction($slug){
    #yourcode
}

OR

You can do one more thing if code in the function is same and nothing to do with the "url"

Route::get('/{slug}', 'HomeController@someAction')->name('YourUniqueRouteName');

work as alias.

Here are some reference Links for more understanding.

Routing#parameters-regular-expression-constraints

Routing#named-routes ( For Route Naming )

Upvotes: 0

Desmond_
Desmond_

Reputation: 49

You can use Named Routes

Route::get('/{slug}', HomeController@someAction)->name('uniqueNameForRoute');

have a look at Laravel naming routes documentation

Upvotes: -1

lagbox
lagbox

Reputation: 50531

You could easily constrain the format of the route parameter using a Regular Expression Constraint:

Route::get('{alias}', 'HomeController@someAction')
    ->where('alias', 'alias1|alias1.html|alias1.php|alias4');

public function someAction($alias)
{
    ...
}

The route will only match if the path is one of your 4 aliases.

Laravel 6.x Docs - Routing - Parameters - Regular Expression Constraints where

Upvotes: 5

Related Questions