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

核能气质少年 提交于 2019-12-12 11:13:05

问题


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?


回答1:


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

}



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



来源:https://stackoverflow.com/questions/38741084/how-to-retrieve-a-url-parameter-from-request-in-laravel-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!