[SOLVED] Laravel Validating Route Parameters
Sep 6, 2022
If you plan to do this directly in your controller method you can do something like:
public function getUser(Request $request)
{
$request->merge(['id' => $request->route('id')]);
$request->validate([
'id' => [
'required',
'exists:users,id'
]
]);
}
To do this in a custom FormRequest
class, add the following:
protected function prepareForValidation()
{
$this->merge(['id' => $this->route('id')]);
}
or if you use model binding, example is Post, then
protected function prepareForValidation()
{
$this->merge(['id' => $this->route('post')]);
}
And in your rules
method:
public function rules()
{
return [
'id' => [
'required',
'exists:post,id'
]
];
}
References:
https://stackoverflow.com/questions/29578153/how-to-validate-route-parameters-in-laravel-5