Search code examples
phplaravellaravel-5middlewareurl-parameters

Laravel getting {id} get parameter in middleware


The problem: I can't get the {id} parameter to be 'found' in the Middleware. My middleware needs to get the {id} param, in order to verify if the Auth::user() is the owner of the specified group.

Request example: groups/admin/open/4 --> group 4 will be opened.

What I have:

Route:

Route::post('groups/admin/open/{id}', 'GroupController@opengroup')->middleware(['auth','owner']);

My middleware ('owner') is still empty.

What I tried: 1. Adding an $id parameter in the function (like you do in Controllers), like so:

public function handle($request, /* Added -> */ $id, Closure $next)
{

    dd(Input::get('id'));

    return $next($request);
}

This returns an error:

Argument 3 passed to App\Http\Middleware\RedirectIfNotOwner::handle() must be an instance of Closure, none given

Different placement of the $id, at the end, results in the error:

Missing argument 3 for App\Http\Middleware\RedirectIfNotOwner::handle()

What I have tried 2: I have thought about is to change my url like this

Request example: groups/admin/open?groupparam=4

And use

Input::get('groupparam');

But this forces me to make changes to my controllers etc. Still this is an option.

Reason for asking: moreover I believe Laravel has the capability to retrieve {id} params in Middleware too, beautifully. I just don't know how.

Can you help me?

Thanks,

Eltyer


Solution

  • You can easily get route parameters in your route middleware with:

    $id = $request->route('id');