wkm*_*wkm 8 php model laravel laravel-4
我试图覆盖我的Post类的save()方法,以便我可以验证将保存到记录的一些字段:
// User.php
<?php
class Post extends Eloquent
{
public function save()
{
// code before save
parent::save();
//code after save
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试在单元测试中运行此方法时,我收到以下错误:
..{"error":{"type":"ErrorException","message":"Declaration of Post::save() should be compatible with that of Illuminate\\Database\\Eloquent\\Model::save()","file":"\/var\/www\/laravel\/app\/models\/Post.php","line":4}}
Run Code Online (Sandbox Code Playgroud)
And*_*yco 20
创建Model.php类,您将在另一个自我验证模型中扩展它
应用程序/模型/ Model.php
class Model extends Eloquent {
/**
* Error message bag
*
* @var Illuminate\Support\MessageBag
*/
protected $errors;
/**
* Validation rules
*
* @var Array
*/
protected static $rules = 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);
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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,调整您的Post模型.
此外,您还需要为此模型定义验证规则.
应用程序/模型/ post.php中
class Post extends Model
{
// validation rules
protected static $rules = [
'name' => 'required'
];
}
Run Code Online (Sandbox Code Playgroud)
控制器方法
由于Model类,Post模型在每次调用save()方法时都会自动验证
public function store()
{
$post = new Post(Input::all());
if ($post->save())
{
return Redirect::route('posts.index');
}
return Redirect::back()->withInput()->withErrors($post->getErrors());
}
Run Code Online (Sandbox Code Playgroud)
这个答案很大程度上基于Jeffrey Way 为Laravel 4提供的Laravel模型验证包.
所有这些人都归功于此!
小智 12
如何Model::save()在Laravel 4.1中覆盖
public function save(array $options = array())
{
parent::save($options);
}
Run Code Online (Sandbox Code Playgroud)
如果要覆盖save()方法,它必须与Model中的save()方法相同:
<?php
public function save(array $options = array()) {}
Run Code Online (Sandbox Code Playgroud)
和; 您还可以使用模型事件挂钩save()调用:http: //laravel.com/docs/eloquent#model-events
| 归档时间: |
|
| 查看次数: |
14027 次 |
| 最近记录: |