Laravel 4-故障覆盖模型';s的保存方法


Laravel 4 - Trouble overriding model's save method

我正试图覆盖Post类的save()方法,以便验证将保存到记录中的一些字段:

// User.php
<?php
class Post extends Eloquent
{
    public function save()
    {
        // code before save
        parent::save(); 
        //code after save
    }
}

当我尝试在单元测试中运行这个方法时,我会得到以下错误:

..{"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}}

创建Model.php类,您将在另一个自验证模型中扩展该类

app/models/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);
    }
}

然后,调整您的Post模型
此外,您还需要为此模型定义验证规则。

app/models/Post.php

class Post extends Model
{
    // validation rules
    protected static $rules = [
        'name' => 'required'
    ];
}

控制器方法
得益于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());
}

这个答案主要基于Jeffrey Way针对Laravel 4的Laravel模型验证包。
所有的功劳都归功于这个人!

如何在Laravel 4.1 中覆盖Model::save()

public function save(array $options = array())
{
   parent::save($options);
}

如果要覆盖save()方法,它必须与Model:中的save()相同

<?php
public function save(array $options = array()) {}

并且;您还可以使用Model Events挂接save()调用:http://laravel.com/docs/eloquent#model-事件