Lumen: how can I get url parameters from middleware - php

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.

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

Passing variable to middleware in laravel 5.x

I would like to send a VARIABLE to my middleware in laravel ,the way I tried is this
Route::get('projects/{id}','projectsController#index')->middleware(['auth', 'project:{id}']);
But all I get in the middleware handle function is '{id}' where as I want the value of the id variable
public function handle($request, Closure $next,$pid)
{
dd($pid);
return $next($request);
}
I read the documentation on middleware for the version of laravel I am using i.e. 5.2 https://laravel.com/docs/5.2/middleware
But the example given there only talks about passing plain strings as parameters
I figured it out , looks like you don't need to pass query pararmets like this, you can simply pull them using the $request variable like so :
public function handle($request, Closure $next)
{
$pid=$request->id;
return $next($request);
}

Laravel getting {id} get parameter in middleware

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');

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');

Categories