[SOLVED] Laravel Validating Route Parameters

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

--

--

Budiaramdhan Rindi

Currently work as Coder since 2011 and still have to learn. Dota 2 and Football Manager are the games I still play to stay fresh.