将所有值保存为大写 Laravel 5+

Lou*_*wki 1 laravel-5

将数据库中的所有值保存为大写的最佳方法是什么。所以在保存之前将所有字符串转换为大写。我看到使用事件或特征的选项可能是最好的,但不太确定如何实现这一点。我不想为我的每个字段创建访问器和修改器。

来自:https : //laracasts.com/discuss/channels/eloquent/listen-to-any-saveupdatecreate-event-for-any-model

trait Trackable {
public static function bootTrackable()
{
    static::creating(function ($model) {
        // blah blah
    });

    static::updating(function ($model) {
        // bleh bleh
    });

    static::deleting(function ($model) {
        // bluh bluh
    });
}
}
Run Code Online (Sandbox Code Playgroud)

我不确定如何获得实际的请求值以将它们转换为大写?

小智 6

正如@Louwki 所说,你可以使用 Trait 来做到这一点,就我而言,我做了这样的事情:

trait SaveToUpper
{
    /**
     * Default params that will be saved on lowercase
     * @var array No Uppercase keys
     */
    protected $no_uppercase = [
        'password',
        'username',
        'email',
        'remember_token',
        'slug',
    ];

    public function setAttribute($key, $value)
    {
        parent::setAttribute($key, $value);
        if (is_string($value)) {
            if($this->no_upper !== null){
                if (!in_array($key, $this->no_uppercase)) {
                    if(!in_array($key, $this->no_upper)){
                        $this->attributes[$key] = trim(strtoupper($value));
                    }
                }
            }else{
                if (!in_array($key, $this->no_uppercase)) {
                    $this->attributes[$key] = trim(strtoupper($value));
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的模型中,您可以使用 'no_upper' 变量指定其他键。像这样:

// YouModel.php
protected $no_upper = ['your','keys','here'];
Run Code Online (Sandbox Code Playgroud)