SoFunction
Updated on 2025-04-09

Laravel learning tutorial accessor

Preface

Eloquent: Introduction to the accessor

Accessories and memory allow you to obtain or setEloquent ModelFormat the attribute value. For example, you might want to do a value before it is stored in the database.Laravel encrypter Perform encryption operations and automatically decrypt this property when you access it through the model.

In addition to customizable accessors and memory,EloquentIt can also be automaticallyDate fieldConvert toCarbon instance, or evenString fieldsConvert toJSON

Accessories & Accessories

Define an accessor

To define an accessor, you need to create a getFooAttribute Method,Foois the camel method of the column name you need to access. In this example, we will define afirst_nameAccessories for properties. This accessor will be attempted to obtain in Eloquent first_name Triggered when attribute value:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
 /**
  * Get the user's first name.
  *
  * @param string $value
  * @return string
  */
 public function getFirstNameAttribute($value)
 {
  return ucfirst($value);
 }
}

As you can see, the original value of the property is passed to the accessor, which allows you to operate on the original value and return the formatted value. You only need simple accessfirst_name The attribute can access the value from the accessor:

$user = App\User::find(1);

$firstName = $user->first_name;

Define a memory

To define a memory, you need to define asetFooAttributeMethod,Foois the name of the camel style of the column you expect to access. So, this time, let'sfirst_name Properties define a memory. This memory will be set in the modelfirst_name Called when the property's value is:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
 /**
  * Set the user's first name.
  *
  * @param string $value
  * @return string
  */
 public function setFirstNameAttribute($value)
 {
  $this->attributes['first_name'] = strtolower($value);
 }
}

The memory will receive the value that will be set to the property, which allows you to operate on this value and set it to the inside of the model.$attributes in the attribute. So, give an example, if we try tofirst_name The property is set toSally:

$user = App\User::find(1);

$user->first_name = 'Sally';


In this example,setFirstNameAttributeMethods will be called and accompanied bySallyvalue. Memory will be appliedstrtolowerMethod lowers the name and sets the value to the internal$attributes in the array.

Date accessor

By default,EloquentWill convertcreated_at andupdated_atListed as CarbonInstance, this instance can provide a variety of useful methods and it inherits from native PHPDataTimekind.

You can customize which fields can be converted automatically, or even disable this conversion completely, you need to rewrite it in your model$dates property:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
 /**
  * The attributes that should be mutated to dates
  *
  * @var array
  */
 protected $dates = ['created_at', 'updated_at', 'deleted_at'];
}

When a column is considered a date, you can set it to a UNIX timestamp, date string (Y-m-d), time string, andDateTime / Carbon Instance and date values ​​will be automatically stored in the database correctly:

$user = App\User::find(1);

$user->deleted_at = Carbon::now();

$user->save();

As mentioned above, when the acquired property is$datesWhen one of the values ​​listed in the property is automatically converted toCarbonInstance, this allows you to use it on propertiesCarbonSome ways to:

$user = App\User::find(1);

return $user->deleted_at->getTimestamp();


By default, the timestamp is formatted asY-m-d H:i:sformat. If you want to customize the format of timestamps, you need to set it in your model$dateFormat property. This property will determine how the date attribute will be stored in the database and when the model is serialized orJSONHow to show when it is transformed:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
 /**
  * The storage format of the model's date columns.
  *
  * @var string
  */
 protected $dateFormat = 'U';
}

Property conversion

You can define it in your model$casts Properties to provide a convenient way to convert properties to common data types.$castsThe attribute should be an array, and the key of each item should be the attribute name that needs to be converted, and the value corresponding to the key should be the type that you need to convert the attribute to. Supported conversion types are:integerrealfloatdoublestringbooleanobjectarraycoolectiondatedatetime,andtimestamp

For example, let's convert is_adminThe property, which stores the value in the database as an integer (0 or 1), we convert it to a boolean:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
 /**
  * The attributes that should be casted to native types.
  *
  * @var array
  */
 protected $casts = [
  'is_admin' => 'boolean',
 ];
}

Now, whenever you visitis_adminWhen an attribute is, its value is converted to a boolean value, even if it is stored in the database:

$user = App\User::find(1);

if ($user->is_admin) {
 //
}

Array conversion

arrayThe type of conversion is especially useful for columns that store serialized JSON values. For example, if the database has a TEXT field and it stores a serialized JSON, if you add the propertyarrayConvert, then when you access this property on the Eloquent model, it will automatically deserialize it into a PHP array:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
 /**
  * The attributes that should be casted to native types.
  *
  * @var array
  */
 protected $casts = [
  'options' => 'array'
 ];
}

When your escape definition is complete, you can accessoptions property, and it will be automatically deserialized from JSON to PHP array. When you set the value tooptions When the attribute is used, the given array is automatically serialized to JSON format and then stored:

$user = App\User::find(1);

$options = $user->options;

$options['key'] = 'value';

$user->options = $options;

$user->save();