Laravel 4.2 での検証にway/databaseパッケージを使用しており、簡単なユーザー登録方法を設定しています。
既に存在する電子メールアドレスで新しいユーザーを作成しようとして、これをテストしています。バリデーターは true を返し、次にエラーを返します。
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'test2@test.com' for key 'users_email_unique' (SQL: insert into `users` (`email`, `password`, `updated_at`, `created_at`) values (test2@test.com, 123, 2015-01-29 11:50:37, 2015-01-29 11:50:37))
これは私のモデルに何か問題がありますか?
コントローラー:
public function store()
{
$user = User::create(Input::only('email', 'password'));
if ($user->hasErrors()){
return Response::json(array(
'error' => $user->getErrors()
));
}
Auth::login($user);
return Response::json(array('success' => 'true'));
}
User.php
モデル:
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Model implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $fillable = array(
'email', 'password'
);
protected static $rules = [
'email' => 'required:unique'
];
//Use this for custom messages
protected static $messages = [
'email.required' => 'An email address is required'
];
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');
}
からの検証モデルは次のway/database
とおりです。
class Model extends Eloquent {
/**
* Error message bag
*
* @var Illuminate\Support\MessageBag
*/
protected $errors;
/**
* Validation rules
*
* @var Array
*/
protected static $rules = array();
/**
* Custom messages
*
* @var Array
*/
protected static $messages = array();
/**
* Validator instance
*
* @var Illuminate\Validation\Validators
*/
protected $validator;
public function __construct(array $attributes = array(), Validator $validator = null)
{
parent::__construct($attributes);
$this->validator = $validator ?: \App::make('validator');
}
/**
* Listen for save event
*/
protected static function boot()
{
parent::boot();
static::saving(function($model)
{
return $model->validate();
});
}
/**
* Validates current attributes against rules
*/
public function validate()
{
$v = $this->validator->make($this->attributes, static::$rules, static::$messages);
if ($v->passes())
{
return true;
}
$this->setErrors($v->messages());
return false;
}
/**
* Set error message bag
*
* @var Illuminate\Support\MessageBag
*/
protected function setErrors($errors)
{
$this->errors = $errors;
}
/**
* Retrieve error message bag
*/
public function getErrors()
{
return $this->errors;
}
/**
* Inverse of wasSaved
*/
public function hasErrors()
{
return ! empty($this->errors);
}
}
誰かが私が間違っていることを指摘できますか?