2016-06-21 24 views
1

我想覆蓋雄辯模型的create()方法來在創建之前更改某些字段(加密它們)。覆蓋雄辯的create()方法

所以在我的模型,我宣佈一個新的方法,這是我改變字段:

public static create(array $data) 
{ 
    // for demonstrating purposes I just prepend a string 
    $data['fieldName'] = 'xxx'.$data['fieldName']; 

    // call the parent' create with the altered data-array 
    return parent::create($data) 
} 

但不知何故,這將導致一個錯誤:

Declaration of App\MyModel::create() should be compatible with Illuminate\Database\Eloquent\Model::create(array $attributes = Array)

我缺少什麼?

回答

2

在方法的參數有一個默認值,所以它應該是這樣的:

public static function create(array $attributes = []) {

但而不是覆蓋你也可以聽一個創建事件或使用賦值函數來設置方法屬性值,它會比覆蓋create方法更好。

+0

OMG laravel已經擁有了我想作爲默認設置烘焙的東西......它是Mutators/Accessors。謝謝。 – stUrb