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);
}
Author by
Alex Lomia
Updated on June 08, 2021Comments
-
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 over 6 yearsI got the error: 'getParameter()' method does not exist. I got the parameters like this:
$request->route()->parameters['item']
-
Syclone over 5 yearsMe too.
$request->route('item')
works for me. Laravel 5.7 -
Subhash Diwakar almost 5 years$request->route()->parameters['item'] and $request->route('item') both works for laravel 5.5 too. but 'getParameter()' does not