Search code examples
phplaravelroutesprefix

Laravel dynamic route with dynamic prefix


I would like to add the customer_id before each group route with the following approach. The customer_id is set as Session::get('customer.id').

Route::group(['prefix' => 'customer/{id}'], function($id) {
        Route::get('reports/default', array('as' => 'customer_reports_path', 'uses' => 'ReportController@getDefault'))->before('customer'); 
        Route::get('data/objects/{$object_id}', array('as' => 'customer_reports_object', 'uses' => 'DataController@getObject'));
});

The first route works as aspected, however, I don't know how to use the second one correctly.

{{ HTML::link(route('customer_reports_object', [Session::get('customer.id'), $object_id], 'Object name') }}

The link still ends in 404.


Solution

  • @MichaelColeman is right $ signs are not allow in route parameters. And here is why:

    The route parameters are found by a Regex, which only matches \w (words) and $ is not included.

    Illuminate\Routing\Route@compileRoute

    $uri = preg_replace('/\{(\w+?)\?\}/', '{$1}', $this->uri);
    

    The solution is obviously to remove the $ (it was probably a typo in the first place)

    Route::get('data/objects/{object_id}'...
    

    And to generate your link correctly. (I also suggest you use the link_to_route function)

    {{ link_to_route('customer_reports_object', 'Object name', [Session::get('customer.id'), $object_id]) }}