xxxxxxxxxx
// Using Form Request
public function rules()
{
return [
'name' => [
'required',
Rule::unique('posts')->ignore($this->id)
],
];
}
xxxxxxxxxx
public function rules()
{
return [
'email' => 'required|email|unique:users,email,'.$this->user->id,
];
}
xxxxxxxxxx
$request->validate([
'name' => 'required',
'email' => 'required|unique:Student',
'password' => 'required|min:6',
'mobile' => 'required',
'address' => 'required',
]);
//unique:table_name
xxxxxxxxxx
use Illuminate\Validation\Rule;
$request->validate([
'phone' => [
'required',
Rule::unique('table_name', 'column_name')->ignore($request->id),
],
]);
xxxxxxxxxx
/**
* Store a new blog post.
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// The blog post is valid...
}
xxxxxxxxxx
use Illuminate\Validation\Rule;
public function rules()
{
return [
'title' => [
'required',
Rule::unique('posts', 'title')->ignore($this->post)
]
];
}
xxxxxxxxxx
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:
public function rules()
{
return [
'email' => 'required|email|unique:users,email,'.$this->user()->id,
];
}
A more elegant way since Laravel 5.7 is:
public function rules()
{
return [
'email' => ['required', 'email', \Illuminate\Validation\Rule::unique('users')->ignore($this->user()->id)]
];
}
xxxxxxxxxx
//$ARG1 - looking in this table
//$ARG2 - checking against this column. Defaults to validation key (eq: email)
//$ARG3 - Aditional WHERE NOT value.
// unique 3rd parameter is the id of the user to be excluded from the validation
public function rules()
{
return [
'email' => 'required|email|unique:users,email,'.$this->user->id,
];
}
// these arguments can also be passed to after 3rd arg:
//$ARG4 - Aditional WHERE NOT field. Defaults to Primary Key
//$ARG5 - Aditional WHERE field 1 - Aditional WHERE value.
xxxxxxxxxx
unique:table,column,except,idColumn
############## Example : ################
############### For Updating
//rules
'email' => 'unique:users,email_address,' . $userId,
############### For Creating
//rules
'email' => 'unique:users,email_address',