/**
* Store a new blog post.
*
* @paramRequest$request
* @returnResponse
*/publicfunctionstore(Request$request){$validatedData=$request->validate(['title'=>'required|unique:posts|max:255','body'=>'required',]);// The blog post is valid...}
Just a side note, most answers to this question talk about email_address while in Laravel's inbuilt auth system, the email field name is just email. Here is an example how you can validate a unique field, i.e. an email on the update:
In a Form Request, you do like this:
public function rules()
{
return [
'email' => 'required|email|unique:users,email,'.$this->user->id,
];
}
Or if you are validating your data in a controller directly:
public function update(Request $request, User $user)
{
$request->validate([
'email' => 'required|email|unique:users,email,'.$user->id,
]);
}
Update: If you are updating the signed in user and aren't injecting the User model into your route, you may encounter undefined property when accessing id on$this->user. In that case,use:publicfunctionrules(){return['email'=>'required|email|unique:users,email,'.$this->user()->id,];}A more elegant way since Laravel 5.7 is:publicfunctionrules(){return['email'=>['required','email',IlluminateValidationRule::unique('users')->ignore($this->user()->id)]];}
unique:table,column,except,idColumn
############## Example : ############################### For Updating //rules'email'=>'unique:users,email_address,'.$userId,############### For Creating //rules'email'=>'unique:users,email_address',
<?phpnamespaceAppHttpRequests;useIlluminateFoundationHttpFormRequest;classStoreUserRequestextendsFormRequest{/**
* Determine if the user is authorized to make this request.
*
* @returnbool
*/publicfunctionauthorize(){returntrue;}/**
* Get the validation rules that apply to the request.
*
* @returnarray
*/publicfunctionrules(){return['name'=>'required','username'=>'required|min:8','email'=>'required|email|unique:users,email,NULL,id,deleted_at,NULL'];}}