voidstate
voidstate

Reputation: 7990

Access a URL Parameter in a Route Prefix from Middleware

I am struggling to access a route prefix parameter from my middleware.

Given this URL: http://www.example.com/api/v1/campaign/40/status, and the following route:

Route::group( [
    'prefix' => 'api/v1'
], function()
{
    Route::group( [
        'prefix' => 'campaign/{campaign}',
        'where' => [ 'campaign' => '[0-9]+' ],
        'middleware' => [
            'inject_campaign'
        ]
    ], function()
    {
        Route::get( 'status', 'CampaignController@getStatus' );
    } );
} );

How do I access the campaign parameter (40 in the example URL) from my inject_campaign middleware? I have the middleware running fine but cannot work out how to access the parameter.

Calling $request->segments() in my middleware gives me the parts of the route but this seems a fragile way of accessing the data. What if the route changes?

Upvotes: 3

Views: 1934

Answers (2)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111899

You can do it using shorter syntax

You can use:

echo $request->route()->campaign;

or even shorter:

echo $request->campaign;

Upvotes: 6

voidstate
voidstate

Reputation: 7990

Got it!

$request->route()->getParameter('campaign')

Upvotes: 0

Related Questions