I'm looking for the best way to enforce unique fields in Laravel form requests, except for when editing. The most obvious example would be only allowing an email address to be used once i.e. each user in a system would need a unique email address.
This is straight-forward to achieve using form requests, by making the field unique:
public function rules()
{
return [
'email' => ['required', 'email', 'unique:users,email'],
];
}
This makes the field required, validates as an email and makes it unique in the user's table. Perfect for creating a new user. But what about editing? It's totally plausible for a user to want to edit their profile and save the same email address again (which is totally valid). But, of course, the unique rule will fire because the email is already "in use" (albeit by the user trying to edit themselves).
Laravel offers a way around this, by passing in the ID of the user table to ignore:
'email' => ['required', 'email', 'unique:users,email,'.$userId]
But how to get the user ID? Maybe this is a bad example because it's trivial to get the logged in user ID, but what about other objects that aren't stored in the session?
If one is using REST, then the ID of the object would be in the URL and available using the route:
$userId = $this->route('order');
But this seems very dirty. And what about other instances where you're not using REST to modify an object? How do you guys enforce uniqueness in form requests when editing objects in Laravel 5?