How to use the request route parameter in Laravel 5 form request?
Solution 1
That's very simple, just use the route()
method. Assuming your route parameter is called id
:
public function authorize(){
$id = $this->route('id');
}
Solution 2
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);
}
Solution 3
Depending on how you defined the parameter in your routes.
For my case below, it would be: 'user'
not 'id'
$id = $this->route('user');
Solution 4
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
Solution 5
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}', ...)
Rohan
Updated on July 09, 2022Comments
-
Rohan almost 2 years
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?
-
Rohan almost 9 yearsThank you for the quick response. I did dd($this->route('id')); in the authorize method. It is returning null. :(
-
lukasgeiter almost 9 yearsIf you're using resource routes the name of the parameter should be the name of the resource. For example
post
if you gotRoute::resource('post', ...)
-
Rohan almost 9 yearsYeah I figured it out eventually by dumping he route object itself. Thank you so much. :)
-
William Turrell over 7 years
$this->route('foo)
doesn't work for me from a Laravel 5.2 Controller ("error evaluating code'). WhereasRoute::current()->getParameter('foo')
does - (see my answer.) Has something changed or do I need to load something else first? -
lukasgeiter over 7 years@WilliamTurrell This question is about getting route parameters in a Form Request method (
authorize
in this case) Theroute
method still exists on the request object but never has on the controller. -
Robert over 4 yearsHad this same issue when using route model binding
-
Suganya Rajasekar about 4 years@Emmanuel Opio try this laravel.com/docs/5.6/routing#implicit-binding