modifier


Define an accessor

  • Define a modifier
  • ##Date Converter
    • Attribute Type Conversion
    • Array & JSON Conversion
    • IntroductionWhen you get or set certain property values ​​in an Eloquent model instance, accessors and modifiers Converter allows you to format Eloquent property values. For example, you might want to use a Laravel encryptor to encrypt a value stored in a database, and then automatically decrypt the value when accessing the property using an Eloquent model.
    In addition to custom accessors and modifiers, Eloquent also automatically converts date field types to
  • Carbon
instances, or

text types to JSON.

Accessors & Modifiers

Define an accessor

To define an accessor, then A getFooAttribute method needs to be created on the model, and the Foo field to be accessed must be named using "camel case". In this example, we will define an accessor for the first_name property. This accessor is automatically called when Eloquent attempts to obtain the first_name property:

<?php
    namespace App;
    use Illuminate\Database\Eloquent\Model;
    class User extends Model{   
     /**
     * 获取用户的姓名.
     *
     * @param  string  $value
     * @return string
     */  
       public function getFirstNameAttribute($value) 
          {      
            return ucfirst($value);   
           }
        }

As you can see, the raw value of the field is passed into the accessor, allowing you to manipulate it and return the result. If you want to get the modified value, you can access the first_name attribute on the model instance:

$user = App\User::find(1);
$firstName = $user->first_name;

Of course, you can also use the accessor to return the new value through the existing attribute value. Calculated values:

/**
 * 获取用户的姓名.
 *
 * @return string
 */
 public function getFullNameAttribute(){ 
    return "{$this->first_name} {$this->last_name}";
  }

{tip} If you need to add these calculated values ​​to the model's array/JSON, you need to append them.

Define a modifier

To define a modifier, you need to define the setFooAttribute method on the model. The Foo fields to be accessed are named using "camelCase". Let's define another modifier for the first_name attribute. This modifier will be automatically called when we try to set the first_name property value on the schema:

<?php
    namespace App;
    use Illuminate\Database\Eloquent\Model;
    class User extends Model{    
      /**
     * 设置用户的姓名.
     *
     * @param  string  $value
     * @return void
     */    
   public function setFirstNameAttribute($value)  
     {      
       $this->attributes['first_name'] = strtolower($value);   
      }
   }

The modifier will get the value that the property has been set to, allowing you to modify it and Its value is set to the $attributes attribute inside the Eloquent model. For example, if we try to set the value of the first_name attribute to Sally:

$user = App\User::find(1);
$user->first_name = 'Sally';

In this example, the setFirstNameAttribute method is calling When accepting the value Sally as a parameter. The modifier then applies the strtolower function and sets the result of the processing to the internal $attributes array.

Date Converter

By default, Eloquent will convert the created_at and updated_at fields into Carbon instances, which inherit from PHP The native DateTime class provides various useful methods. You can add other date properties by setting the model's $dates property:

<?php
    namespace App;
    use Illuminate\Database\Eloquent\Model;
    class User extends Model{   
     /**
     * 应该转换为日期格式的属性.
     *
     * @var array
     */  
     protected $dates = [       
      'seen_at',  
      ];
    }

{tip} You can add other date properties by setting the model's public property $timestamps Set the value to false to disable the default created_at and updated_at timestamps.

When a field is in date format, you can set the value to a UNIX timestamp, datetime (Y-m-d) string, or DateTime / Carbon instance. Date values ​​will be correctly formatted and saved to your database:

$user = App\User::find(1);
$user->deleted_at = now();
$user->save();

As mentioned above, when the obtained attributes are included in the $dates attribute, they will be automatically converted is a Carbon instance, allowing you to use any Carbon method on the property:

$user = App\User::find(1);
return $user->deleted_at->getTimestamp();

Date format

By default, the timestamp will Formatted in the form 'Y-m-d H:i:s'. If you need to customize the timestamp format, set the $dateFormat property in the model. This property determines how the date attribute will be saved in the database and formatted when the model is serialized into an array or JSON:

<?php
    namespace App;
    use Illuminate\Database\Eloquent\Model;
    class Flight extends Model{   
     /**
     * 模型日期字段的保存格式.
     *
     * @var string
     */  
     protected $dateFormat = 'U';
    }

Attribute type conversion

The $casts attribute in the model provides a convenient way to convert attributes to common data types. $casts The property should be an array, and the keys of the array are the names of the properties that need to be cast, and the values ​​are the data types you want to cast. The data types that support conversion are: integer, real, float, double, decimal:<digits>, string, boolean, object, array, collection, date, datetime, and timestamp. When you need to convert to the decimal type, you need to define the number of decimal places, such as: decimal:2

Example, let us convert it to an integer (## The is_admin attribute stored in the database in the form #0 or 1) is converted into a Boolean value.

    <?php   
     namespace App;    
     use Illuminate\Database\Eloquent\Model;    
     class User extends Model  
       {       
        /**
         * 这个属性应该被转换为原生类型.
         *
         * @var array
         */       
          protected $casts = [        
              'is_admin' => 'boolean',        
              ];    
            }

Now when you access the

is_admin attribute, although the value stored in the database is an integer type, the return value will always be converted to a Boolean type:

    $user = App\User::find(1); 
    if ($user->is_admin) {      
      //  
      }

Array & JSON Conversion

Conversions of the array type are very useful when you store serialized JSON data in a database. For example: If your database has a JSON or TEXT field type that is serialized to JSON, and the array type conversion is added to the Eloquent model, then when It will be automatically converted into a PHP array when you access it.

    <?php  
      namespace App;    
      use Illuminate\Database\Eloquent\Model;    
      class User extends Model    {       
       /**
         * 这个属性应该被转换为原生类型.
         *
         * @var array
         */        
        protected $casts = [          
          'options' => 'array',     
            ];   
         }

Once the conversion is defined, it will automatically deserialize from the JSON type to a PHP array when you access the options property. When you set the value of the options attribute, the given array will also be automatically serialized into JSON type storage:

    $user = App\User::find(1);    
    $options = $user->options;    
    $options['key'] = 'value';    
    $user->options = $options;    
    $user->save();

Date Conversion

When using the date or datetime attribute, you can specify the format of the date. This format will be used to serialize the model into an array or JSON:

    /**
     * 这个属性应该被转化为原生类型.
     *
     * @var array
     */    
     protected $casts = [     
        'created_at' => 'datetime:Y-m-d',  
         ];
This article was first published on the LearnKu.com website.