Laravel: Passing down a parameter in a route prefix/route group

Working through an issue today, I needed to pass a parameter through to sub-routes inside a route group in Laravel. It’s not very well documented, and very powerful.

E.g. a signed in user can have a few apps. App with ID 3, 6, 10 etc.

Anything they do, once they’ve chosen which app they’re working on, should include the app ID in the URL.

Route::group(['prefix'=>'/apps/{id}'],function(){

    Route::get('/test', function($id) {
        echo $id;
    });
});

There it is, nice and easy. the $id parameter from the group will pass down to the individual endpoints. Now we can have URLs like https://www.mydomain.com/apps/5/summary, which is so much nicer and self describing than relying on a session variable for the ‘selected’ app. Now multiple users in the same team can share links with each other, or a user can bookmark pages that are useful to them without losing state.

 

 

Published