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

4

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?

Lewislewisite answered 3/8, 2016 at 10:32 Comment(2)
"request->param('item') " Do you mean request GET/POST parameter?Cloyd
@pbwned just a url parameter. For example extract the id part from /item/{id} routeLewislewisite
F
18
public function handle(Request $request, Closure $next)
{
    $itemId = $request->item;
    //..............

}
Flawy answered 3/8, 2016 at 10:36 Comment(0)
M
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}'

Metabolize answered 3/8, 2016 at 10:38 Comment(3)
I got the error: 'getParameter()' method does not exist. I got the parameters like this: $request->route()->parameters['item']Turney
Me too. $request->route('item') works for me. Laravel 5.7Southey
$request->route()->parameters['item'] and $request->route('item') both works for laravel 5.5 too. but 'getParameter()' does notAsclepius
P
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);
}
Perfection answered 8/6, 2021 at 7:51 Comment(0)
L
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');

}

Lupelupee answered 7/11, 2023 at 8:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.