Reputation: 12598
I am trying to use unique on an email address in Laravel 5.5 validation like this..
$rules = [
'email' => 'email|unique:users,email,
];
This is working and is checking the 'users' table in the 'email' column
But if the email address is the same as the currently saved one then this also fails validation.
Is there a way I can add an exception rule to the validation to ignore $user-email?
Upvotes: 0
Views: 7686
Reputation: 929
Just add $this->route('id') as the third parameter
if your route was defined like this:
Route::put('{company}', 'CompanyController@update')
->name('update');
then your parameter name is "company"
So in your FormRequest:
public function rules()
{
$rules = [
'url' => [
'required',
'url',
'unique:companies,url,'.$this->route('company') ?? 0
],
];
// dd($rules); << check yourself
return $rules;
}
This FormRequest works the same for insert or update.
this line will instruct to ignore "0" in case of insert
$this->route('company') ?? 0
Upvotes: -1
Reputation: 5599
The unique
rule takes a third parameter: a record to ignore, see "Forcing A Unique Rule To Ignore A Given ID".
Pass in the ID of the record you do not wish to be included in the unique
test, e.g:
$rules = [
'email' => 'email|unique:users,email,' . $user->id
];
Upvotes: 11