Reputation: 290
I have validation rules for my model:
protected $fillable = array('username','firstname','lastname',"street","city","country","birthday","email");
public static $rules = array(
'username' => 'required|between:4,16|unique:users',
'email' => 'required|email|unique:users',
'password' => 'required|min:4',
'firstname' => 'required|alpha_num|between:2,16',
'lastname' => 'required|alpha_num|between:2,32',
);
and my update method:
public function update($id)
{
$user = User::find($id);
$data = Input::all();
if ( isset($data['firstname']) ) {
$user->firstname = $data['firstname'];
}
$success = $user->update();
if ( $success ) {
return Response::json(array('error' => false, 'user' => $user->toArray()), 200 );
} else {
return Response::json(array('error' => true, 'message' => $user->errors()->all()), 400 );
}
}
And now I'm getting an error:
{
"error": true,
"message": [
"The username has already been taken.",
"The email has already been taken."
]
}
So, the question is: How can I update only one field of the model?
UPDATE:
As I'm using Ardent (https://github.com/laravelbook/ardent) I could do:
$success = $user->updateUniques();
and everything works now.
Upvotes: 2
Views: 4814
Reputation: 159
protected function setConditionalRules($model)
{
$id = $model->getKey();
foreach(['email', 'username'] as $field)
{
$this->validator->sometimes($field, $this->rules[$field].",$id", function($input) use($model, $field)
{
if($model->exists)
{
$this->validator->setRules(array_except($this->validator->getRules(), [$field]));
return true;
}
return false;
});
}
}
Upvotes: 0
Reputation: 23942
The error message says that when updating the model, validation unique requirements detects that username and email already exists. To avoid that, append the currently updating id instance to the make the validator. In the validator use a parameter to detect if you are updating or creating it, and send the user id in the first case, then you can use:
Forcing A Unique Rule To Ignore A Given ID
'username' => 'required|between:4,16|unique:users,'.$userId,
'email' => 'required|email|unique:users,'.$userId,
More detail here: https://stackoverflow.com/a/22406205/1165509
Upvotes: 2