vish4071
vish4071

Reputation: 5277

Defining Route in Laravel

I have a "weird" situation here. I need to handle following routes in the same way:

domain.com/common/p1
domain.com/common/p1/p2
domain.com/common/p1/p2/p3

Which means, basically, route should be something like:

Route::get('common/{path}', function ($path) {
    //should execute for all paths after common
});

Is there any regex which I can use?

Upvotes: 3

Views: 146

Answers (5)

Alex
Alex

Reputation: 4266

See more: https://laravel.com/docs/5.8/routing

You can use:

Route::get('common/{path}', function ($path) {
    //should execute for all paths after common
})->where('path', '(.*)');

Hope it help you.

Upvotes: 2

Mike Foxtech
Mike Foxtech

Reputation: 1651

The Laravel routing component allows all characters except /. You must explicitly allow / to be part of your placeholder using a where condition regular expression:

Route::get('common/{path}', function ($path) {
    //should execute for all paths after common
})->where('path', '.*');

Upvotes: 1

Jigar
Jigar

Reputation: 3261

I think you can achieve this using below code.

Route::any('/common/{args?}', function($args){
   $args = explode('/', $args);
   // do your code by passing argument to controller
})->where('args', '(.*)');

Upvotes: 0

Mohd Qayyoom Khan
Mohd Qayyoom Khan

Reputation: 78

yes, you can..

Route::get('common/{path}', function ($path) {
//should execute for all paths after common
})->where('path', 'YOUR REGEX GOES HERE');

Upvotes: 0

Bram Verstraten
Bram Verstraten

Reputation: 1557

You are looking for optional parameters.

Your code would look something like:

Route::get('common/{path1?}/{path2?}/{path3?}', function ($path1=null, $path2=null, $path3=null) {
    //
});

For unlimited parameters use:

Route::get('common/{path?}', 'Controller@Method')->where('path', '.*');

This will result in an array of paths in your controller method.

Upvotes: 1

Related Questions