【问题标题】:How to set default uuid on save model Laravel 5.3+?如何在保存模型 Laravel 5.3+ 上设置默认 uuid?
【发布时间】:2017-07-08 04:08:42
【问题描述】:

我如何在模型上设置自己的属性在保存之前,但仅限于我创建新行/条目时?

示例 PHP:

class foo extends controller {
    // ..
    public function create () {
        $user = new User();
        $user->name = 'Jack';
        $user->lastname = 'Smith';
        $user->save();
    }
    // ..
}

型号:

class User extends Model {
    // ...
    public function beforeSave() {
        $this->token = uuid();
    }
    // ...
}

表:

CREATE TABLE User
    (
      `uuid` varchar(55),
      `name` varchar(55) NOT NULL,
      `lastname` varchar(55) NOT NULL,
      primary key (`uuid`)
    )
;

【问题讨论】:

标签: php laravel laravel-5 model


【解决方案1】:

据我所知,在您的模型中添加方法 boot()

public static function boot()
{
    parent::boot();

    self::creating(function($model){
        // ... code here
    });

}

就像this solutionthis one一样

或者你可以使用model observers

【讨论】:

    猜你喜欢
    • 2017-02-16
    • 1970-01-01
    • 2018-02-18
    • 2013-09-15
    • 1970-01-01
    • 2014-12-05
    • 2017-10-21
    • 2023-02-24
    • 2014-08-17
    相关资源
    最近更新 更多