Laravel getting {id} get parameter in middleware - php

The problem: I can't get the {id} parameter to be 'found' in the Middleware. My middleware needs to get the {id} param, in order to verify if the Auth::user() is the owner of the specified group.
Request example: groups/admin/open/4 --> group 4 will be opened.
What I have:
Route:
Route::post('groups/admin/open/{id}', 'GroupController#opengroup')->middleware(['auth','owner']);
My middleware ('owner') is still empty.
What I tried:
1. Adding an $id parameter in the function (like you do in Controllers), like so:
public function handle($request, /* Added -> */ $id, Closure $next)
{
dd(Input::get('id'));
return $next($request);
}
This returns an error:
Argument 3 passed to App\Http\Middleware\RedirectIfNotOwner::handle() must be an instance of Closure, none given
Different placement of the $id, at the end, results in the error:
Missing argument 3 for App\Http\Middleware\RedirectIfNotOwner::handle()
What I have tried 2: I have thought about is to change my url like this
Request example: groups/admin/open?groupparam=4
And use
Input::get('groupparam');
But this forces me to make changes to my controllers etc. Still this is an option.
Reason for asking: moreover I believe Laravel has the capability to retrieve {id} params in Middleware too, beautifully. I just don't know how.
Can you help me?
Thanks,
Eltyer

You can easily get route parameters in your route middleware with:
$id = $request->route('id');

Related

Can we pass method parameter of controller optional

I'm using Laravel and I have a question running on my mind.
Basically, we create a Controller method like this:
public function index(User $user)
{
if(!empty($user)){ ... }
...
}
And we call this method by passing the $user as parameter to this method.
But is it possible to call the parameter optional. I mean if $user didn't pass, still the method works.
So in order to do that, do we have to create two web routes? Because by default, when we pass parameter we have to define that too in the route uri:
Route::get("/{user}", "HomeController#index");
Route::get("/", "HomeController#index");
So how to do this in Laravel? Is it possible or not?
I would really appreciate any idea or suggestion from you guys...
Thanks.
You can make a method parameter optional, yes. That's a PHP feature:
PHP - default function/method parameters
So in your code:
public function index(User $user = null)
{
if(!empty($user)){ ... }
...
}
It seems you want to call HomeController#index in both cases, isn't that misleading? If you visit /1 it will load user with ID 1 and show the homepage. What could be the use-case of that?
As John Lobo suggested, the route should better be /user/{user} to remove that ambiguity.
As an aside: Use Auth to get current user
If this is meant to load the current user: You can load the current user in every controller with Auth. There is no need to pass the user explicitly as a parameter if that works better for you:
$user = Auth::user();
See Laravel docs: Authentication

Middleware not working as expected - Laravel

This is driving me crazy as I think I'm doing the right thing but its not working correctly.
I have a route with a middleware attached to it like below;
Route::get('post/{id}/{name}', 'BlogController#post')->name('blog-post')->middleware('blogGuard');
As you can see I've defined 2 route params
In my controller I have below;
public function post () {
return view('pages.blog.post');
}
With the middleware defined like this;
public function handle($request, Closure $next)
{
if (is_null($request->input('id')) ||
is_null($request->input('name'))) {
return redirect()->route('blog-home');
}
return $next($request);
}
Now if I click on a link like so; http://blog.example.co.uk/post/153/firstpost the middleware should not fire correct?
This is not the case. The middleware executes and I'm redirected. But if I remove the middleware then I'm able to access the page.
Any help appreciated.
If you are trying to access route parameters you probably want to explicitly get them from the route.
$request->route('id'); // pulls the $route->parameter('id');
$request->route('name'); // pulls the $route->parameter('name');
$request->id will check the request inputs before falling back to returning a route parameter.
$request->input('id') will only check the input sources for the request and not the route params.
If you use $request->id expecting to get the route param 'id', one could break your logic by passing id=anythinghere to the querystring or adding a 'id' var to a post request.
Try this
if (!$request->id ||
!$request->name)

Laravel 5 - Getting URL Parameters in Middleware on Resources

Let's say that I have a resource defined in my Routes as:
Route::resource('account', 'AccountController', ['only'=> ['index','update']]);
And then I have the Middleware attached to the Controller from within as:
public function __construct() {
$this->middleware('BeforeAccount', ['only' => ['update']]);
}
Let's say I want to access the uri parameter that happens after account (i.e. example.com/account/2) within my Middleware - how do I go about grabbing that variable?
You can use the following code to achieve that:
public function handle($request, Closure $next)
{
$account_id = $request->route()->parameter('accounts');
//...
}
Since the handle method receives the Request object as the first argument. The middleware gets executed only after the route has been matched so the Request object contains the current route and no need to match the route again using Route::getRoutes()->match($request).
Doing this way you don't have to supply the \Request object:
Route::current()->parameter('parameter');

Lumen: how can I get url parameters from middleware

This is my routes.php:
$app->get('/users/{id}/', ['middleware' => 'example', function () {
return "users";
}]);
This is the handle function in the middleware:
public function handle($request, Closure $next)
{
// I would like to get the value of the url parameter {id} here
return $next($request);
}
Is there a way I can get the parameter id from my middleware?
* Edit *
I'm using Lumen 5.1.0.
There are some conventional ways in Laravel doesn't work on Lumen. And get parameter form URI in middleware is one of them. In Laravel, I just need to call $request->id, it will work like magic. But here in order to get parameter in Lumen, I need to do something like this:
$request->route()[2]['id']
If the $request value passed in is an instance of Illuminate\Http\Request, which I think it might be, that class has a method called input(), which lets you do exactly that:
You should try this:
$id = $request->input('id');
i think the latest lumen 5.6 official tutorial about middleware is no longer applicable, and out of date.

How to use the request route parameter in Laravel 5 form request?

I am new to Laravel 5 and I am trying to use the new Form Request to validate all forms in my application.
Now I am stuck at a point where I need to DELETE a resource and I created a DeleteResourceRequest for just to use the authorize method.
The problem is that I need to find what id is being requested in the route parameter but I cannot see how to get that in to the authorize method.
I can use the id in the controller method like so:
public function destroy($id, DeletePivotRequest $request)
{
Resource::findOrFail($id);
}
But how to get this to work in the authorize method of the Form Request?
That's very simple, just use the route() method. Assuming your route parameter is called id:
public function authorize(){
$id = $this->route('id');
}
You can accessing a Route parameter Value via Illuminate\Http\Request instance
public function destroy($id, DeletePivotRequest $request)
{
if ($request->route('id'))
{
//
}
Resource::findOrFail($id);
}
Depending on how you defined the parameter in your routes.
For my case below, it would be: 'user' not 'id'
$id = $this->route('user');
Laravel 5.2, from within a controller:
use Route;
...
Route::current()->getParameter('id');
I've found this useful if you want to use the same controller method for more than one route with more than one URL parameter, and perhaps all parameters aren't always present or may appear in a different order...
i.e. getParameter('id')will give you the correct answer, regardless of {id}'s position in the URL.
See Laravel Docs: Accessing the Current Route
After testing the other solutions, seems not to work for laravel 8, but this below works
Route::getCurrentRoute()->id
assuming your route is
Route::post('something/{id}', ...)
I came here looking for an answer and kind of found it in the comments, so wanted to clarify for others using a resource route trying to use this in a form request
as mentioned by lukas in his comment:
Given a resource controller Route::resource('post', ...) the parameter you can use will be named post
This was usefull to me but not quite complete. It appears that the parameter will be the singular version of the last part of the resource stub.
In my case, the route was defined as $router->resource('inventory/manufacturers', 'API\Inventory\ManufacturersController');
And the parameter available was manufacturer (the singular version of the last part of the stub inventory/manufacturers)
you will get parameter id if you call
request()->route('id')
OR
$this->route('id')
if you're using resource routing, you need to call with the resource name
// eg: resource
Route::resource('users', App\Http\Controllers\UserController::class);
$this->route('user')
in Terminal write
php artisan route:list
to see what is your param name
Then use
$this->route('sphere') to get param

Categories