在存储库之前,这是我用来创建和验证模型的方式:
public function store()
{
$user = new User(Input::all());
$user->password = Input::get('password');
if( !$user->save() ) {
return Redirect::back()
->withInput()
->withErrors($user->errors);
}
return Redirect::route('users.index')
->with('successMessages', 'User "'.$user->first_name.'" created.');
}
此代码由
一个基本模型:
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class BaseModel extends Eloquent {
public $errors;
public function __construct(array $attributes = array()) {
parent::__construct($attributes);
}
public static function boot() {
parent::boot();
static::saving(function ($data) {
return $data->validate();
});
}
public function validate() {
$validation = Validator::make($this->attributes, $this->rules);
if($validation->passes()) return true;
$this->errors = $validation->messages();
return false;
}
}
通过在启动时创建保存事件,您可以验证模型并在 save() 上返回 true 或 false;
用户模型:
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends BaseModel implements UserInterface, RemindableInterface {
protected $table = 'users';
public $guarded = [
'password',
'password_confirmation',
];
public $rules = array(
'first_name' => 'required|min:3',
'last_name' => 'required|min:3',
'email' => 'required|min:6',
);
protected $hidden = array('password');
public function setPasswordAttribute($string)
{
$this->attributes['password'] = Hash::make($string);
}
}
还有我的一些代码layout.blade.php
:
@if( Session::has('errors') )
You have some errors:
@foreach( Session::get('errors')->all() as $error )
<div class="alert alert-block alert-error fade in">
<button data-dismiss="alert" class="close" type="button">×</button>
<p>{{ $error->message }}</p>
</div>
@endforeach
@endif
@if( isset($successMessage) )
<div class="alert alert-block alert-success fade in">
<button data-dismiss="alert" class="close" type="button">×</button>
<p>{{ $successMessage }}</p>
</div>
@endif
@if( isset($errorMessage) )
<div class="alert alert-block alert-error fade in">
<button data-dismiss="alert" class="close" type="button">×</button>
<p>{{ $errorMessage }}</p>
</div>
@endif
实际上,这个刀片代码并没有那么大,它由一些刀片 _partials 和一个模板帮助器类提供,看起来更像这样:
{{ Template::notifications('error', Session::get('errors')) }}
{{ isset($successMessage) ? Template::notify('success', $successMessage) : '' }}
{{ isset($errorMessage) ? Template::notify('error', $errorMessage) : '' }}
使用验证,您可以节省一些行,并且永远不需要记住再次验证您的输入。