user391986
user391986

Reputation: 30896

Laravel routes matching everything after prefix

I'm trying to match a path in a URL something like the following

My HTTP Request

http://localhost/myprefix/extra/x/x/x/x/x/2/3/2/

routes.php

Route::group(
    ['prefix' => 'myprefix'],
    function () {
        Route::get('extra/{path}', ['as' => 'myprefix.one', 'uses' => 'MyController@index']);
        Route::get('extraOTher/{path}', ['as' => 'myprefix.two', 'uses' => 'MyController@indexOther']);
    }
);

MyController.php

public function index($path)
{
    // $path should be extra/x/x/x/x/x/2/3/2/
}

This keeps giving me error

NotFoundHttpException in RouteCollection.php line 145:

How can I get this working? I read somewhere about :any and :all but I could not get these working either.

Upvotes: 2

Views: 2156

Answers (1)

itachi
itachi

Reputation: 6393

A little bit hacky.

Routes.php:

Route::group(
    ['prefix' => 'myprefix'],
    function () {
        Route::get('extra/{path}', ['as' => 'myprefix.one', 'uses' => 'MyController@index']);
        Route::get('extraOTher/{path}', ['as' => 'myprefix.two', 'uses' => 'MyController@indexOther']);
    }
);

Add a pattern.

Route::pattern('path', '[a-zA-Z0-9-/]+');

Now it will catch all the routes.

Controller.php:

public function index($path)
{
    echo $path; // outputs x/x/x/2/3/4/ whatever there is. 

    // To get the prefix with all the segements,

    echo substr(parse_url(\Request::url())['path'],1);
}

Not elegant. but it should do the trick.

Upvotes: 3

Related Questions