Accessors and modifiers


brief introduction

Accessors and modifiers allow you to format Eloquent properties when you get model properties or set their values. For example, you may want to use Larravel Encryptor Encrypt the data stored in the database, and automatically decrypt when accessing in the Eloquent model.

In addition to custom accessors and modifiers, Eloquent can also automatically convert date fields to Carbon Instance or even Convert text to JSON

Accessors&Modifiers

Define Accessors

To define an accessor, you need to create a getFooAttribute Method, where Foo Is the name of the field you want to access (using the hump naming rule). In this example, we will provide first_name Property defines an accessor that gets first_name Is automatically called by Eloquent:

 <? php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { /** *Get the user's name * * @param  string  $value * @return string */ public function getFirstNameAttribute($value) { return ucfirst($value); } }

As you can see, the original value of this field is passed to the accessor, and then the processed value is returned. To access this value, simply access first_name That is:

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

Of course, you can also use accessors to convert existing attributes into new, processed values:

 /** *Get the user's full name * * @return string */ public function getFullNameAttribute() { return "{$this->first_name} {$this->last_name}"; }

Note: If you want to add these calculated values to the model in array/JSON format, you need to Manually append them

Define Modifiers

To define a modifier, you need to define it in the model setFooAttribute Method, where Foo Is the field you want to access (using the hump naming convention). Next let's first_name Attribute defines a modifier when we set the first_name The modifier is automatically called when a value is assigned:

 <? php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { /** *Set the user's name * * @param  string  $value * @return string */ public function setFirstNameAttribute($value) { $this->attributes['first_name'] = strtolower($value); } }

This modifier gets the attribute value to be set, allowing you to manipulate the value and set the internal attribute value of Eloquent model as the value after the operation. For example, if you try to set Sally Of first_name Properties:

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

In this example, setFirstNameAttribute The method will be called, and the passed in parameter is Sally , the modifier calls strtolower Function and set the processed value to the value of the internal property.

Date Modifier

By default, Eloquent will convert created_at and updated_at The value of the column is Carbon Instance, this class inherits from PHP native Datetime Class, and provides various useful methods. You can customize which fields are automatically adjusted and modified, or even override the $dates Property completely prohibits adjustment:

 <? php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { /** *The attribute should be adjusted to date * * @var array */ protected $dates = [ 'seen_at' ]; }

Note: You can set the public properties of the model $timestamps Value is false To disable the default created_at and updated_at Timestamp.

If the field is in date format, you can set its value as UNIX timestamp, date string( Y-m-d ), date time string, Datetime / Carbon Instance and date values will be automatically stored in the database in the correct format:

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

As mentioned above, when access is listed in $dates The attributes in the array will be automatically converted to Carbon Instance and allows you to use any Carbon Method of class:

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

Date format

By default, the timestamp format is 'Y-m-d H:i:s' , if you need to customize the timestamp format, set it in the model $dateFormat Attribute, which determines the format of the date attribute when it is stored in the database and serialized as an array or JSON:

 <? php namespace App; use Illuminate\Database\Eloquent\Model; class Flight extends Model { /** *Storage format of model date * * @var string */ protected $dateFormat = 'U'; }

Attribute conversion

In the model $casts Attributes provide a convenient way to convert attribute fields to common data types. $casts Property is an array format. Its key is the name of the property to be converted. Its value is the type you want to convert. The currently supported conversion types include: integer , real , float , double , decimal:<digits> , string , boolean , object array collection date datetime and timestamp Convert to decimal The number of digits must be defined when( decimal:2 )。

For example, let's convert is_admin Property, set it by integer Value( zero or one )Convert to boolean Value:

 <? php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { /** *Attributes that should be converted to primitive types * * @var array */ protected $casts = [ 'is_admin' => 'boolean', ]; }

Now? is_admin Property is always converted to boolean , even if the underlying value stored in the database is integer

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

Array&JSON conversion

array Type conversion is particularly useful when processing fields stored in serialized JSON format, for example, if the database has a JSON or TEXT The field type contains serialized JSON, add array Type conversion to this attribute will automatically deserialize its value into a PHP array when accessing its value in the Eloquent model:

 <? php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { /** *Attributes that should be converted to primitive types * * @var array */ protected $casts = [ 'options' => 'array', ]; }

After the type conversion is defined, access options Properties will be automatically deserialized from JSON to PHP arrays. Conversely, when you set options Property, the given array will be automatically converted to JSON for storage:

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

Date conversion

When using date or datetime When converting types, you can specify the format of the date, which will be displayed in the Used when the model is serialized as an array or JSON

 /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'created_at' => 'datetime:Y-m-d', ];

Recommended articles:


give the thumbs-up Cancel Like Collection Cancel Collection

<<Previous: API resource class

>>Next: serialize