11

I want to perform certain operations with a model in a middleware. Here is an example of what I want to achieve:

public function handle($request, Closure $next)
{
    $itemId = $request->param('item'); // <-- invalid code, serves for illustration purposes only
    $item   = Item::find($itemId);

    if($item->isBad()) return redirect(route('dont_worry'));

    return $next($request);
}

My question is, how can I retrieve the desired parameter from the $request?

2
  • "request->param('item') " Do you mean request GET/POST parameter? Commented Aug 3, 2016 at 10:35
  • @pbwned just a url parameter. For example extract the id part from /item/{id} route Commented Aug 3, 2016 at 10:41

4 Answers 4

18
public function handle(Request $request, Closure $next)
{
    $itemId = $request->item;
    //..............

}
Sign up to request clarification or add additional context in comments.

Comments

13

If the parameter is part of a URL and this code is being used in Middleware, you can access the parameter by it's name from the route given:

public function handle($request, Closure $next)
{
    $itemId = $request->route()->getParameter('item');
    $item   = Item::find($itemId);

    if($item->isBad()) return redirect(route('dont_worry'));

    return $next($request);
}

This is based on having a route like: '/getItem/{item}'

3 Comments

I got the error: 'getParameter()' method does not exist. I got the parameters like this: $request->route()->parameters['item']
Me too. $request->route('item') works for me. Laravel 5.7
$request->route()->parameters['item'] and $request->route('item') both works for laravel 5.5 too. but 'getParameter()' does not
3

Use this after Laravel 5.5

public function handle($request, Closure $next)
{
    $item = Item::find($request->route()->parameter('item'));
    if($item->isBad()) return redirect(route('dont_worry'));
    return $next($request);
}

Comments

1

In some cases, we can use the below method also to get the parameter,


public function handle(Request $request, Closure $next)
{
    $itemId = $request->query('item');

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.