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
?
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.
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.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
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.
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);
}
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}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With