Home » Php » php – How to use the request route parameter in Laravel 5 form request?

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

Posted by: admin April 23, 2020 Leave a comment

Questions:

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?

How to&Answers:

That’s very simple, just use the route() method. Assuming your route parameter is called id:

public function authorize(){
    $id = $this->route('id');
}

Answer:

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

Answer:

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

Answer:

Depending on how you defined the parameter in your routes.

For my case below, it would be: 'user' not 'id'

$id = $this->route('user');

enter image description here

Answer:

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)