Using form requests? Let's figure out how to access values that you're resolving with route model binding.
Here's an example form request to update a user's profile:
class ProfileUpdateRequest extends FormRequest
{
//...
public function rules(): array
{
return [
'email' => ['required', 'email', Rule::unique('users', 'email')],
];
}
}
Let's imagine this request was sent down with a route that looks like this:
Route::patch('/users/{user}', ProfileUpdateController::class);
How do we access the route model binding value for user
in our form request class?
Simple, since a form request is an extension of a Laravel Request
, here's how:
class ProfileUpdateRequest extends FormRequest
{
//...
public function rules(): array
{
return [
'email' => [
'required',
'email',
Rule::unique('users', 'email')->ignore($this->user->id)
],
];
}
}
We can now ignore the user's current email in the unique check by accessing $this->user
, which gives us back the entire resolved User
model.