Laravel 数据转换器

Laravel Data Converter

我有一个模型可以将 7 位数字作为字符串保存。我想创建转换器,使用户与该字符串之间的交互类似于 ##-###-##。因此,如果模型持有 1234567,用户将看到 12-345-67,如果用户输入的数字为 76-543-21,则模型将其存储为 7654321

许多其他平台都包含转换器来处理此类任务。我怎样才能在 Laravel 5.2 中做到这一点?我在文档中进行了搜索,但没有找到任何有用的解决方案。

Laravel 5.2支持转换器吗?我应该如何处理这种转换?

是的,Laravel支持"converters",实际上它们被称为mutators。 Mutators 可以定义为 setters 和 getters。取决于您希望如何转换值。

在您的特定情况下,您将需要使用 setter 和 getter 增变器,因为您将在将值存储到数据库之前和读取它们时对其进行转换:

class User extends Model
{
    /**
     * Set the models name attribute.
     * @param  string  $value
     */
    public function setNameAttribute($value)
    {
        if ( /* do regex to check if the value that user has entered is already in the format ##-###-## */) {                
            $this->attributes['name'] = $value; // Already formatted, no need to do anything
        } else {
            $this->attributes['name'] = ....; // convert to correct format
        }
    }

    /**
     * Get the models name attribute.
     *
     * @param  string  $value
     * @return string
     */
     public function getNameAttribute($value)
     {
         return /* convert value to ##-###-## format */;
     }
}

您可以通过以驼峰式命名您的函数 set[Column name]Attributeget[Column name]Attribute 来指定增变器。因此,如果您的列名称是例如 name,那么您的增变器将被命名为 public funtion setNameAttribute($value)public funtion getNameAttribute($value)