imJohnBon's avatar

Lumen override route parameter in middleware

I'm currently trying to implement a Middleware in Lumen that makes it so that if someone types in a URL like this:

/users/self

It will replace "self" with the current logged in users ID, so when it gets to the controller the $id parameter is equal to a real ID instead of "self". However, I'm having a really hard time figuring out how to replace "self" with the ID by the time it gets to the controller. I thought maybe something like this would work:

public function handle($request, Closure $next)
{
    if ($request->route()[2]['id'] === 'self') {
        $request->route()[2]['id'] = $this->getCurrentUsersId();
    }

    return $next($request);
}

However, it does not update the requests 'id' value like I hoped it would. Does anyone have any advice on this?

0 likes
4 replies
ChristophAust's avatar

Why do you do this in a middleware? Do you want this to be adapted to multiple endpoints? If not I would just implement this as a static route and point it to the get method of my controller.

imJohnBon's avatar

@ChristophAust Correct, this needs to be applied to roughly a dozen endpoints. Middleware seems the most appropriate since it's reusable and it's whole purpose is to affect the request before it hits your controller method.

ismaail's avatar

So far the only workaround I used to solve this issue is to inject the parameter into the $request

in the Middleware file

public function handle($request, Closure $next)
{
    $request->id = $request->route()[2]['id'];
    if ($request->id === 'self') {
        $request->id = $this->getCurrentUsersId();
    }

    return $next($request);
}

and in the Controller file

public function actionMethod($id, Request $request)
{
    dd($request->id);
}

Please or to participate in this conversation.