Victor_Arcas's avatar

[L5] How to get url parameters at middleware

I have these routes

Route::group(['prefix' => '{id}/questions', 'middleware' => 'groupExists'], function(){
                    Route::post( '/', 'QuestionsController@create' );
                    Route::post( '/searches', 'QuestionsController@search' );
                });   

And I have this middleware intercepting them

class GroupExists implements Middleware{
    
    public function handle($request, Closure $next) {
        $group = Group::find($request->input('id')); // This is null
        $groupNotFound = !$group;

        if( $groupNotFound )
              ...

$request->input('id') is not working. How can I get the /{id}/ parameter of the route url?

Note: the id param is the id of a "group". These "questions" are related to a "group". The Route::group of the image is nested in another Route::group. The route is correct because it returns if I put a return "foo" in it.

0 likes
5 replies
bestmomo's avatar
Level 52

Try that :

$group = $request->id
13 likes
willotter's avatar

Just to save someone the same issue. If you are using the Route::resource('routeName') syntax for your routes your id parameter is named routeName.

You can access all the parameters with $request->route()->parameters()

11 likes
matiascx's avatar

$request->route()->parameters() will return all the parameters you can take

3 likes
Gifted's avatar

In reference to @willotter https://laracasts.com/@willotter

Brilliant answer I used this in conjunction with

#Our Route

 Route::get('postcodes/{postcode?}','show');

#Our Middleware or even controller and $params represent url params

 $params = $request->route()->parameters();

#Check if empty params and get postcode for validation

        $params = $request->route()->parameters();
        function getPostcode($params){
            if(sizeof($params) == 0){
                $postcode = false;
                return $postcode;
            }else{
                 #Map postcode
                $object = (object) $params;
                $postcode = $object->postcode;
                return $postcode;
            }
        }

so I get postcode by just this way

$postcode =  getPostcode($params);
1 like

Please or to participate in this conversation.