Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 384
Alex Lomia Avatar asked Aug 03 '16 10:08

Alex Lomia


People also ask

How to get data from current URL in Laravel?

Tools Sometimes you might want to find the current URL and to write condition. This way, you can add active class to current url link. You also might want to pass data with query string parameters to view instead of session in web application. This is easy way to get data in Laravel.

What is fullurlwithoutquery() method in Laravel?

Now, recently with this PR, Laravel 8.x is coming with a method called fullUrlWithoutQuery () which does exactly opposite of the fullUrlWithQuery () method. i.e it removes the specified query string parameters from the request URL. So, if we use the fullUrlWithoutQuery () the previous example, it would look like so.

What are the new features in Laravel 5 Tinker?

What are the new features in Laravel 5.5 Laravel Tinker with PHP Artisan command to update user details Laravel 5.4 User Role and Permissions with Spatie Laravel Permission Laravel 5 force download file with the response helper method Force update updated_at column using Eloquent Touch method

How to change or add parameters to url while return?

Suppose you want to change or add parameters to url while return, use \Request::fullUrlWithQuery () method with parameter of associative array. The array will be added as query string in url.


2 Answers

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);
}
like image 125
Arjun bhati Avatar answered Oct 23 '22 03:10

Arjun bhati


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

like image 26
Justin Origin Broadband Avatar answered Oct 23 '22 03:10

Justin Origin Broadband