How to retrieve a url parameter from request in Laravel 5?

34,551

Solution 1

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

}

Solution 2

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}'

Solution 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);
}
Share:
34,551
Alex Lomia
Author by

Alex Lomia

Updated on June 08, 2021

Comments

  • Alex Lomia
    Alex Lomia almost 3 years

    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?

  • Raghavendra N
    Raghavendra N over 6 years
    I got the error: 'getParameter()' method does not exist. I got the parameters like this: $request->route()->parameters['item']
  • Syclone
    Syclone over 5 years
    Me too. $request->route('item') works for me. Laravel 5.7
  • Subhash Diwakar
    Subhash Diwakar almost 5 years
    $request->route()->parameters['item'] and $request->route('item') both works for laravel 5.5 too. but 'getParameter()' does not