Eloquent: Mutators & Casting

Introduction

Accessors, mutators, and attribute casting allow you to transform Eloquent attribute values when you retrieve or set them on model instances. For example, you may want to use the Laravel encrypter to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Eloquent model. Or, you may want to convert a JSON string that is stored in your database to an array when it is accessed via your Eloquent model.

Accessors & Mutators

Defining An Accessor

An accessor transforms an Eloquent attribute value when it is accessed. To define an accessor, create a protected method on your model to represent the accessible attribute. This method name should correspond to the "camel case" representation of the true underlying model attribute / database column when applicable.

In this example, we'll define an accessor for the first_name attribute. The accessor will automatically be called by Eloquent when attempting to retrieve the value of the first_name attribute. All attribute accessor / mutator methods must declare a return type-hint of Illuminate\Database\Eloquent\Casts\Attribute:

1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Database\Eloquent\Casts\Attribute;
6use Illuminate\Database\Eloquent\Model;
7 
8class User extends Model
9{
10 /**
11 * Get the user's first name.
12 *
13 * @return \Illuminate\Database\Eloquent\Casts\Attribute
14 */
15 protected function firstName(): Attribute
16 {
17 return Attribute::make(
18 get: fn ($value) => ucfirst($value),
19 );
20 }
21}
1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Database\Eloquent\Casts\Attribute;
6use Illuminate\Database\Eloquent\Model;
7 
8class User extends Model
9{
10 /**
11 * Get the user's first name.
12 *
13 * @return \Illuminate\Database\Eloquent\Casts\Attribute
14 */
15 protected function firstName(): Attribute
16 {
17 return Attribute::make(
18 get: fn ($value) => ucfirst($value),
19 );
20 }
21}

All accessor methods return an Attribute instance which defines how the attribute will be accessed and, optionally, mutated. In this example, we are only defining how the attribute will be accessed. To do so, we supply the get argument to the Attribute class constructor.

As you can see, the original value of the column is passed to the accessor, allowing you to manipulate and return the value. To access the value of the accessor, you may simply access the first_name attribute on a model instance:

1use App\Models\User;
2 
3$user = User::find(1);
4 
5$firstName = $user->first_name;
1use App\Models\User;
2 
3$user = User::find(1);
4 
5$firstName = $user->first_name;
lightbulb

If you would like these computed values to be added to the array / JSON representations of your model, you will need to append them.

Building Value Objects From Multiple Attributes

Sometimes your accessor may need to transform multiple model attributes into a single "value object". To do so, your get closure may accept a second argument of $attributes, which will be automatically supplied to the closure and will contain an array of all of the model's current attributes:

1use App\Support\Address;
2use Illuminate\Database\Eloquent\Casts\Attribute;
3 
4/**
5 * Interact with the user's address.
6 *
7 * @return \Illuminate\Database\Eloquent\Casts\Attribute
8 */
9protected function address(): Attribute
10{
11 return Attribute::make(
12 get: fn ($value, $attributes) => new Address(
13 $attributes['address_line_one'],
14 $attributes['address_line_two'],
15 ),
16 );
17}
1use App\Support\Address;
2use Illuminate\Database\Eloquent\Casts\Attribute;
3 
4/**
5 * Interact with the user's address.
6 *
7 * @return \Illuminate\Database\Eloquent\Casts\Attribute
8 */
9protected function address(): Attribute
10{
11 return Attribute::make(
12 get: fn ($value, $attributes) => new Address(
13 $attributes['address_line_one'],
14 $attributes['address_line_two'],
15 ),
16 );
17}

Accessor Caching

When returning value objects from accessors, any changes made to the value object will automatically be synced back to the model before the model is saved. This is possible because Eloquent retains instances returned by accessors so it can return the same instance each time the accessor is invoked:

1use App\Models\User;
2 
3$user = User::find(1);
4 
5$user->address->lineOne = 'Updated Address Line 1 Value';
6$user->address->lineTwo = 'Updated Address Line 2 Value';
7 
8$user->save();
1use App\Models\User;
2 
3$user = User::find(1);
4 
5$user->address->lineOne = 'Updated Address Line 1 Value';
6$user->address->lineTwo = 'Updated Address Line 2 Value';
7 
8$user->save();

However, you may sometimes wish to enable caching for primitive values like strings and booleans, particularly if they are computationally intensive. To accomplish this, you may invoke the shouldCache method when defining your accessor:

1protected function hash(): Attribute
2{
3 return Attribute::make(
4 get: fn ($value) => bcrypt(gzuncompress($value)),
5 )->shouldCache();
6}
1protected function hash(): Attribute
2{
3 return Attribute::make(
4 get: fn ($value) => bcrypt(gzuncompress($value)),
5 )->shouldCache();
6}

If you would like to disable the object caching behavior of attributes, you may invoke the withoutObjectCaching method when defining the attribute:

1/**
2 * Interact with the user's address.
3 *
4 * @return \Illuminate\Database\Eloquent\Casts\Attribute
5 */
6protected function address(): Attribute
7{
8 return Attribute::make(
9 get: fn ($value, $attributes) => new Address(
10 $attributes['address_line_one'],
11 $attributes['address_line_two'],
12 ),
13 )->withoutObjectCaching();
14}
1/**
2 * Interact with the user's address.
3 *
4 * @return \Illuminate\Database\Eloquent\Casts\Attribute
5 */
6protected function address(): Attribute
7{
8 return Attribute::make(
9 get: fn ($value, $attributes) => new Address(
10 $attributes['address_line_one'],
11 $attributes['address_line_two'],
12 ),
13 )->withoutObjectCaching();
14}

Defining A Mutator

A mutator transforms an Eloquent attribute value when it is set. To define a mutator, you may provide the set argument when defining your attribute. Let's define a mutator for the first_name attribute. This mutator will be automatically called when we attempt to set the value of the first_name attribute on the model:

1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Database\Eloquent\Casts\Attribute;
6use Illuminate\Database\Eloquent\Model;
7 
8class User extends Model
9{
10 /**
11 * Interact with the user's first name.
12 *
13 * @return \Illuminate\Database\Eloquent\Casts\Attribute
14 */
15 protected function firstName(): Attribute
16 {
17 return Attribute::make(
18 get: fn ($value) => ucfirst($value),
19 set: fn ($value) => strtolower($value),
20 );
21 }
22}
1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Database\Eloquent\Casts\Attribute;
6use Illuminate\Database\Eloquent\Model;
7 
8class User extends Model
9{
10 /**
11 * Interact with the user's first name.
12 *
13 * @return \Illuminate\Database\Eloquent\Casts\Attribute
14 */
15 protected function firstName(): Attribute
16 {
17 return Attribute::make(
18 get: fn ($value) => ucfirst($value),
19 set: fn ($value) => strtolower($value),
20 );
21 }
22}

The mutator closure will receive the value that is being set on the attribute, allowing you to manipulate the value and return the manipulated value. To use our mutator, we only need to set the first_name attribute on an Eloquent model:

1use App\Models\User;
2 
3$user = User::find(1);
4 
5$user->first_name = 'Sally';
1use App\Models\User;
2 
3$user = User::find(1);
4 
5$user->first_name = 'Sally';

In this example, the set callback will be called with the value Sally. The mutator will then apply the strtolower function to the name and set its resulting value in the model's internal $attributes array.

Mutating Multiple Attributes

Sometimes your mutator may need to set multiple attributes on the underlying model. To do so, you may return an array from the set closure. Each key in the array should correspond with an underlying attribute / database column associated with the model:

1use App\Support\Address;
2use Illuminate\Database\Eloquent\Casts\Attribute;
3 
4/**
5 * Interact with the user's address.
6 *
7 * @return \Illuminate\Database\Eloquent\Casts\Attribute
8 */
9protected function address(): Attribute
10{
11 return Attribute::make(
12 get: fn ($value, $attributes) => new Address(
13 $attributes['address_line_one'],
14 $attributes['address_line_two'],
15 ),
16 set: fn (Address $value) => [
17 'address_line_one' => $value->lineOne,
18 'address_line_two' => $value->lineTwo,
19 ],
20 );
21}
1use App\Support\Address;
2use Illuminate\Database\Eloquent\Casts\Attribute;
3 
4/**
5 * Interact with the user's address.
6 *
7 * @return \Illuminate\Database\Eloquent\Casts\Attribute
8 */
9protected function address(): Attribute
10{
11 return Attribute::make(
12 get: fn ($value, $attributes) => new Address(
13 $attributes['address_line_one'],
14 $attributes['address_line_two'],
15 ),
16 set: fn (Address $value) => [
17 'address_line_one' => $value->lineOne,
18 'address_line_two' => $value->lineTwo,
19 ],
20 );
21}

Attribute Casting

Attribute casting provides functionality similar to accessors and mutators without requiring you to define any additional methods on your model. Instead, your model's $casts property provides a convenient method of converting attributes to common data types.

The $casts property should be an array where the key is the name of the attribute being cast and the value is the type you wish to cast the column to. The supported cast types are:

  • array
  • AsStringable::class
  • boolean
  • collection
  • date
  • datetime
  • immutable_date
  • immutable_datetime
  • decimal:<precision>
  • double
  • encrypted
  • encrypted:array
  • encrypted:collection
  • encrypted:object
  • float
  • integer
  • object
  • real
  • string
  • timestamp

To demonstrate attribute casting, let's cast the is_admin attribute, which is stored in our database as an integer (0 or 1) to a boolean value:

1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Database\Eloquent\Model;
6 
7class User extends Model
8{
9 /**
10 * The attributes that should be cast.
11 *
12 * @var array
13 */
14 protected $casts = [
15 'is_admin' => 'boolean',
16 ];
17}
1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Database\Eloquent\Model;
6 
7class User extends Model
8{
9 /**
10 * The attributes that should be cast.
11 *
12 * @var array
13 */
14 protected $casts = [
15 'is_admin' => 'boolean',
16 ];
17}

After defining the cast, the is_admin attribute will always be cast to a boolean when you access it, even if the underlying value is stored in the database as an integer:

1$user = App\Models\User::find(1);
2 
3if ($user->is_admin) {
4 //
5}
1$user = App\Models\User::find(1);
2 
3if ($user->is_admin) {
4 //
5}

If you need to add a new, temporary cast at runtime, you may use the mergeCasts method. These cast definitions will be added to any of the casts already defined on the model:

1$user->mergeCasts([
2 'is_admin' => 'integer',
3 'options' => 'object',
4]);
1$user->mergeCasts([
2 'is_admin' => 'integer',
3 'options' => 'object',
4]);
exclamation

Attributes that are null will not be cast. In addition, you should never define a cast (or an attribute) that has the same name as a relationship.

Stringable Casting

You may use the Illuminate\Database\Eloquent\Casts\AsStringable cast class to cast a model attribute to a fluent Illuminate\Support\Stringable object:

1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Database\Eloquent\Casts\AsStringable;
6use Illuminate\Database\Eloquent\Model;
7 
8class User extends Model
9{
10 /**
11 * The attributes that should be cast.
12 *
13 * @var array
14 */
15 protected $casts = [
16 'directory' => AsStringable::class,
17 ];
18}
1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Database\Eloquent\Casts\AsStringable;
6use Illuminate\Database\Eloquent\Model;
7 
8class User extends Model
9{
10 /**
11 * The attributes that should be cast.
12 *
13 * @var array
14 */
15 protected $casts = [
16 'directory' => AsStringable::class,
17 ];
18}

Array & JSON Casting

The array cast is particularly useful when working with columns that are stored as serialized JSON. For example, if your database has a JSON or TEXT field type that contains serialized JSON, adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model:

1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Database\Eloquent\Model;
6 
7class User extends Model
8{
9 /**
10 * The attributes that should be cast.
11 *
12 * @var array
13 */
14 protected $casts = [
15 'options' => 'array',
16 ];
17}
1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Database\Eloquent\Model;
6 
7class User extends Model
8{
9 /**
10 * The attributes that should be cast.
11 *
12 * @var array
13 */
14 protected $casts = [
15 'options' => 'array',
16 ];
17}

Once the cast is defined, you may access the options attribute and it will automatically be deserialized from JSON into a PHP array. When you set the value of the options attribute, the given array will automatically be serialized back into JSON for storage:

1use App\Models\User;
2 
3$user = User::find(1);
4 
5$options = $user->options;
6 
7$options['key'] = 'value';
8 
9$user->options = $options;
10 
11$user->save();
1use App\Models\User;
2 
3$user = User::find(1);
4 
5$options = $user->options;
6 
7$options['key'] = 'value';
8 
9$user->options = $options;
10 
11$user->save();

To update a single field of a JSON attribute with a more terse syntax, you may use the -> operator when calling the update method:

1$user = User::find(1);
2 
3$user->update(['options->key' => 'value']);
1$user = User::find(1);
2 
3$user->update(['options->key' => 'value']);

Array Object & Collection Casting

Although the standard array cast is sufficient for many applications, it does have some disadvantages. Since the array cast returns a primitive type, it is not possible to mutate an offset of the array directly. For example, the following code will trigger a PHP error:

1$user = User::find(1);
2 
3$user->options['key'] = $value;
1$user = User::find(1);
2 
3$user->options['key'] = $value;

To solve this, Laravel offers an AsArrayObject cast that casts your JSON attribute to an ArrayObject class. This feature is implemented using Laravel's custom cast implementation, which allows Laravel to intelligently cache and transform the mutated object such that individual offsets may be modified without triggering a PHP error. To use the AsArrayObject cast, simply assign it to an attribute:

1use Illuminate\Database\Eloquent\Casts\AsArrayObject;
2 
3/**
4 * The attributes that should be cast.
5 *
6 * @var array
7 */
8protected $casts = [
9 'options' => AsArrayObject::class,
10];
1use Illuminate\Database\Eloquent\Casts\AsArrayObject;
2 
3/**
4 * The attributes that should be cast.
5 *
6 * @var array
7 */
8protected $casts = [
9 'options' => AsArrayObject::class,
10];

Similarly, Laravel offers an AsCollection cast that casts your JSON attribute to a Laravel Collection instance:

1use Illuminate\Database\Eloquent\Casts\AsCollection;
2 
3/**
4 * The attributes that should be cast.
5 *
6 * @var array
7 */
8protected $casts = [
9 'options' => AsCollection::class,
10];
1use Illuminate\Database\Eloquent\Casts\AsCollection;
2 
3/**
4 * The attributes that should be cast.
5 *
6 * @var array
7 */
8protected $casts = [
9 'options' => AsCollection::class,
10];

Date Casting

By default, Eloquent will cast the created_at and updated_at columns to instances of Carbon, which extends the PHP DateTime class and provides an assortment of helpful methods. You may cast additional date attributes by defining additional date casts within your model's $casts property array. Typically, dates should be cast using the datetime or immutable_datetime cast types.

When defining a date or datetime cast, you may also specify the date's format. This format will be used when the model is serialized to an array or JSON:

1/**
2 * The attributes that should be cast.
3 *
4 * @var array
5 */
6protected $casts = [
7 'created_at' => 'datetime:Y-m-d',
8];
1/**
2 * The attributes that should be cast.
3 *
4 * @var array
5 */
6protected $casts = [
7 'created_at' => 'datetime:Y-m-d',
8];

When a column is cast as a date, you may set the corresponding model attribute value to a UNIX timestamp, date string (Y-m-d), date-time string, or a DateTime / Carbon instance. The date's value will be correctly converted and stored in your database.

You may customize the default serialization format for all of your model's dates by defining a serializeDate method on your model. This method does not affect how your dates are formatted for storage in the database:

1/**
2 * Prepare a date for array / JSON serialization.
3 *
4 * @param \DateTimeInterface $date
5 * @return string
6 */
7protected function serializeDate(DateTimeInterface $date)
8{
9 return $date->format('Y-m-d');
10}
1/**
2 * Prepare a date for array / JSON serialization.
3 *
4 * @param \DateTimeInterface $date
5 * @return string
6 */
7protected function serializeDate(DateTimeInterface $date)
8{
9 return $date->format('Y-m-d');
10}

To specify the format that should be used when actually storing a model's dates within your database, you should define a $dateFormat property on your model:

1/**
2 * The storage format of the model's date columns.
3 *
4 * @var string
5 */
6protected $dateFormat = 'U';
1/**
2 * The storage format of the model's date columns.
3 *
4 * @var string
5 */
6protected $dateFormat = 'U';

Date Casting, Serialization, & Timezones

By default, the date and datetime casts will serialize dates to a UTC ISO-8601 date string (1986-05-28T21:05:54.000000Z), regardless of the timezone specified in your application's timezone configuration option. You are strongly encouraged to always use this serialization format, as well as to store your application's dates in the UTC timezone by not changing your application's timezone configuration option from its default UTC value. Consistently using the UTC timezone throughout your application will provide the maximum level of interoperability with other date manipulation libraries written in PHP and JavaScript.

If a custom format is applied to the date or datetime cast, such as datetime:Y-m-d H:i:s, the inner timezone of the Carbon instance will be used during date serialization. Typically, this will be the timezone specified in your application's timezone configuration option.

Enum Casting

exclamation

Enum casting is only available for PHP 8.1+.

Eloquent also allows you to cast your attribute values to PHP Enums. To accomplish this, you may specify the attribute and enum you wish to cast in your model's $casts property array:

1use App\Enums\ServerStatus;
2 
3/**
4 * The attributes that should be cast.
5 *
6 * @var array
7 */
8protected $casts = [
9 'status' => ServerStatus::class,
10];
1use App\Enums\ServerStatus;
2 
3/**
4 * The attributes that should be cast.
5 *
6 * @var array
7 */
8protected $casts = [
9 'status' => ServerStatus::class,
10];

Once you have defined the cast on your model, the specified attribute will be automatically cast to and from an enum when you interact with the attribute:

1if ($server->status == ServerStatus::Provisioned) {
2 $server->status = ServerStatus::Ready;
3 
4 $server->save();
5}
1if ($server->status == ServerStatus::Provisioned) {
2 $server->status = ServerStatus::Ready;
3 
4 $server->save();
5}

Casting Arrays Of Enums

Sometimes you may need your model to store an array of enum values within a single column. To accomplish this, you may utilize the AsEnumArrayObject or AsEnumCollection casts provided by Laravel:

1use App\Enums\ServerStatus;
2use Illuminate\Database\Eloquent\Casts\AsEnumCollection;
3 
4/**
5 * The attributes that should be cast.
6 *
7 * @var array
8 */
9protected $casts = [
10 'statuses' => AsEnumCollection::class.':'.ServerStatus::class,
11];
1use App\Enums\ServerStatus;
2use Illuminate\Database\Eloquent\Casts\AsEnumCollection;
3 
4/**
5 * The attributes that should be cast.
6 *
7 * @var array
8 */
9protected $casts = [
10 'statuses' => AsEnumCollection::class.':'.ServerStatus::class,
11];

Encrypted Casting

The encrypted cast will encrypt a model's attribute value using Laravel's built-in encryption features. In addition, the encrypted:array, encrypted:collection, encrypted:object, AsEncryptedArrayObject, and AsEncryptedCollection casts work like their unencrypted counterparts; however, as you might expect, the underlying value is encrypted when stored in your database.

As the final length of the encrypted text is not predictable and is longer than its plain text counterpart, make sure the associated database column is of TEXT type or larger. In addition, since the values are encrypted in the database, you will not be able to query or search encrypted attribute values.

Key Rotation

As you may know, Laravel encrypts strings using the key configuration value specified in your application's app configuration file. Typically, this value corresponds to the value of the APP_KEY environment variable. If you need to rotate your application's encryption key, you will need to manually re-encrypt your encrypted attributes using the new key.

Query Time Casting

Sometimes you may need to apply casts while executing a query, such as when selecting a raw value from a table. For example, consider the following query:

1use App\Models\Post;
2use App\Models\User;
3 
4$users = User::select([
5 'users.*',
6 'last_posted_at' => Post::selectRaw('MAX(created_at)')
7 ->whereColumn('user_id', 'users.id')
8])->get();
1use App\Models\Post;
2use App\Models\User;
3 
4$users = User::select([
5 'users.*',
6 'last_posted_at' => Post::selectRaw('MAX(created_at)')
7 ->whereColumn('user_id', 'users.id')
8])->get();

The last_posted_at attribute on the results of this query will be a simple string. It would be wonderful if we could apply a datetime cast to this attribute when executing the query. Thankfully, we may accomplish this using the withCasts method:

1$users = User::select([
2 'users.*',
3 'last_posted_at' => Post::selectRaw('MAX(created_at)')
4 ->whereColumn('user_id', 'users.id')
5])->withCasts([
6 'last_posted_at' => 'datetime'
7])->get();
1$users = User::select([
2 'users.*',
3 'last_posted_at' => Post::selectRaw('MAX(created_at)')
4 ->whereColumn('user_id', 'users.id')
5])->withCasts([
6 'last_posted_at' => 'datetime'
7])->get();

Custom Casts

Laravel has a variety of built-in, helpful cast types; however, you may occasionally need to define your own cast types. To create a cast, execute the make:cast Artisan command. The new cast class will be placed in your app/Casts directory:

1php artisan make:cast Json
1php artisan make:cast Json

All custom cast classes implement the CastsAttributes interface. Classes that implement this interface must define a get and set method. The get method is responsible for transforming a raw value from the database into a cast value, while the set method should transform a cast value into a raw value that can be stored in the database. As an example, we will re-implement the built-in json cast type as a custom cast type:

1<?php
2 
3namespace App\Casts;
4 
5use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
6 
7class Json implements CastsAttributes
8{
9 /**
10 * Cast the given value.
11 *
12 * @param \Illuminate\Database\Eloquent\Model $model
13 * @param string $key
14 * @param mixed $value
15 * @param array $attributes
16 * @return array
17 */
18 public function get($model, $key, $value, $attributes)
19 {
20 return json_decode($value, true);
21 }
22 
23 /**
24 * Prepare the given value for storage.
25 *
26 * @param \Illuminate\Database\Eloquent\Model $model
27 * @param string $key
28 * @param array $value
29 * @param array $attributes
30 * @return string
31 */
32 public function set($model, $key, $value, $attributes)
33 {
34 return json_encode($value);
35 }
36}
1<?php
2 
3namespace App\Casts;
4 
5use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
6 
7class Json implements CastsAttributes
8{
9 /**
10 * Cast the given value.
11 *
12 * @param \Illuminate\Database\Eloquent\Model $model
13 * @param string $key
14 * @param mixed $value
15 * @param array $attributes
16 * @return array
17 */
18 public function get($model, $key, $value, $attributes)
19 {
20 return json_decode($value, true);
21 }
22 
23 /**
24 * Prepare the given value for storage.
25 *
26 * @param \Illuminate\Database\Eloquent\Model $model
27 * @param string $key
28 * @param array $value
29 * @param array $attributes
30 * @return string
31 */
32 public function set($model, $key, $value, $attributes)
33 {
34 return json_encode($value);
35 }
36}

Once you have defined a custom cast type, you may attach it to a model attribute using its class name:

1<?php
2 
3namespace App\Models;
4 
5use App\Casts\Json;
6use Illuminate\Database\Eloquent\Model;
7 
8class User extends Model
9{
10 /**
11 * The attributes that should be cast.
12 *
13 * @var array
14 */
15 protected $casts = [
16 'options' => Json::class,
17 ];
18}
1<?php
2 
3namespace App\Models;
4 
5use App\Casts\Json;
6use Illuminate\Database\Eloquent\Model;
7 
8class User extends Model
9{
10 /**
11 * The attributes that should be cast.
12 *
13 * @var array
14 */
15 protected $casts = [
16 'options' => Json::class,
17 ];
18}

Value Object Casting

You are not limited to casting values to primitive types. You may also cast values to objects. Defining custom casts that cast values to objects is very similar to casting to primitive types; however, the set method should return an array of key / value pairs that will be used to set raw, storable values on the model.

As an example, we will define a custom cast class that casts multiple model values into a single Address value object. We will assume the Address value has two public properties: lineOne and lineTwo:

1<?php
2 
3namespace App\Casts;
4 
5use App\ValueObjects\Address as AddressValueObject;
6use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
7use InvalidArgumentException;
8 
9class Address implements CastsAttributes
10{
11 /**
12 * Cast the given value.
13 *
14 * @param \Illuminate\Database\Eloquent\Model $model
15 * @param string $key
16 * @param mixed $value
17 * @param array $attributes
18 * @return \App\ValueObjects\Address
19 */
20 public function get($model, $key, $value, $attributes)
21 {
22 return new AddressValueObject(
23 $attributes['address_line_one'],
24 $attributes['address_line_two']
25 );
26 }
27 
28 /**
29 * Prepare the given value for storage.
30 *
31 * @param \Illuminate\Database\Eloquent\Model $model
32 * @param string $key
33 * @param \App\ValueObjects\Address $value
34 * @param array $attributes
35 * @return array
36 */
37 public function set($model, $key, $value, $attributes)
38 {
39 if (! $value instanceof AddressValueObject) {
40 throw new InvalidArgumentException('The given value is not an Address instance.');
41 }
42 
43 return [
44 'address_line_one' => $value->lineOne,
45 'address_line_two' => $value->lineTwo,
46 ];
47 }
48}
1<?php
2 
3namespace App\Casts;
4 
5use App\ValueObjects\Address as AddressValueObject;
6use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
7use InvalidArgumentException;
8 
9class Address implements CastsAttributes
10{
11 /**
12 * Cast the given value.
13 *
14 * @param \Illuminate\Database\Eloquent\Model $model
15 * @param string $key
16 * @param mixed $value
17 * @param array $attributes
18 * @return \App\ValueObjects\Address
19 */
20 public function get($model, $key, $value, $attributes)
21 {
22 return new AddressValueObject(
23 $attributes['address_line_one'],
24 $attributes['address_line_two']
25 );
26 }
27 
28 /**
29 * Prepare the given value for storage.
30 *
31 * @param \Illuminate\Database\Eloquent\Model $model
32 * @param string $key
33 * @param \App\ValueObjects\Address $value
34 * @param array $attributes
35 * @return array
36 */
37 public function set($model, $key, $value, $attributes)
38 {
39 if (! $value instanceof AddressValueObject) {
40 throw new InvalidArgumentException('The given value is not an Address instance.');
41 }
42 
43 return [
44 'address_line_one' => $value->lineOne,
45 'address_line_two' => $value->lineTwo,
46 ];
47 }
48}

When casting to value objects, any changes made to the value object will automatically be synced back to the model before the model is saved:

1use App\Models\User;
2 
3$user = User::find(1);
4 
5$user->address->lineOne = 'Updated Address Value';
6 
7$user->save();
1use App\Models\User;
2 
3$user = User::find(1);
4 
5$user->address->lineOne = 'Updated Address Value';
6 
7$user->save();
lightbulb

If you plan to serialize your Eloquent models containing value objects to JSON or arrays, you should implement the Illuminate\Contracts\Support\Arrayable and JsonSerializable interfaces on the value object.

Array / JSON Serialization

When an Eloquent model is converted to an array or JSON using the toArray and toJson methods, your custom cast value objects will typically be serialized as well as long as they implement the Illuminate\Contracts\Support\Arrayable and JsonSerializable interfaces. However, when using value objects provided by third-party libraries, you may not have the ability to add these interfaces to the object.

Therefore, you may specify that your custom cast class will be responsible for serializing the value object. To do so, your custom cast class should implement the Illuminate\Contracts\Database\Eloquent\SerializesCastableAttributes interface. This interface states that your class should contain a serialize method which should return the serialized form of your value object:

1/**
2 * Get the serialized representation of the value.
3 *
4 * @param \Illuminate\Database\Eloquent\Model $model
5 * @param string $key
6 * @param mixed $value
7 * @param array $attributes
8 * @return mixed
9 */
10public function serialize($model, string $key, $value, array $attributes)
11{
12 return (string) $value;
13}
1/**
2 * Get the serialized representation of the value.
3 *
4 * @param \Illuminate\Database\Eloquent\Model $model
5 * @param string $key
6 * @param mixed $value
7 * @param array $attributes
8 * @return mixed
9 */
10public function serialize($model, string $key, $value, array $attributes)
11{
12 return (string) $value;
13}

Inbound Casting

Occasionally, you may need to write a custom cast class that only transforms values that are being set on the model and does not perform any operations when attributes are being retrieved from the model.

Inbound only custom casts should implement the CastsInboundAttributes interface, which only requires a set method to be defined. The make:cast Artisan command may be invoked with the --inbound option to generate an inbound only cast class:

1php artisan make:cast Hash --inbound
1php artisan make:cast Hash --inbound

A classic example of an inbound only cast is a "hashing" cast. For example, we may define a cast that hashes inbound values via a given algorithm:

1<?php
2 
3namespace App\Casts;
4 
5use Illuminate\Contracts\Database\Eloquent\CastsInboundAttributes;
6 
7class Hash implements CastsInboundAttributes
8{
9 /**
10 * The hashing algorithm.
11 *
12 * @var string
13 */
14 protected $algorithm;
15 
16 /**
17 * Create a new cast class instance.
18 *
19 * @param string|null $algorithm
20 * @return void
21 */
22 public function __construct($algorithm = null)
23 {
24 $this->algorithm = $algorithm;
25 }
26 
27 /**
28 * Prepare the given value for storage.
29 *
30 * @param \Illuminate\Database\Eloquent\Model $model
31 * @param string $key
32 * @param array $value
33 * @param array $attributes
34 * @return string
35 */
36 public function set($model, $key, $value, $attributes)
37 {
38 return is_null($this->algorithm)
39 ? bcrypt($value)
40 : hash($this->algorithm, $value);
41 }
42}
1<?php
2 
3namespace App\Casts;
4 
5use Illuminate\Contracts\Database\Eloquent\CastsInboundAttributes;
6 
7class Hash implements CastsInboundAttributes
8{
9 /**
10 * The hashing algorithm.
11 *
12 * @var string
13 */
14 protected $algorithm;
15 
16 /**
17 * Create a new cast class instance.
18 *
19 * @param string|null $algorithm
20 * @return void
21 */
22 public function __construct($algorithm = null)
23 {
24 $this->algorithm = $algorithm;
25 }
26 
27 /**
28 * Prepare the given value for storage.
29 *
30 * @param \Illuminate\Database\Eloquent\Model $model
31 * @param string $key
32 * @param array $value
33 * @param array $attributes
34 * @return string
35 */
36 public function set($model, $key, $value, $attributes)
37 {
38 return is_null($this->algorithm)
39 ? bcrypt($value)
40 : hash($this->algorithm, $value);
41 }
42}

Cast Parameters

When attaching a custom cast to a model, cast parameters may be specified by separating them from the class name using a : character and comma-delimiting multiple parameters. The parameters will be passed to the constructor of the cast class:

1/**
2 * The attributes that should be cast.
3 *
4 * @var array
5 */
6protected $casts = [
7 'secret' => Hash::class.':sha256',
8];
1/**
2 * The attributes that should be cast.
3 *
4 * @var array
5 */
6protected $casts = [
7 'secret' => Hash::class.':sha256',
8];

Castables

You may want to allow your application's value objects to define their own custom cast classes. Instead of attaching the custom cast class to your model, you may alternatively attach a value object class that implements the Illuminate\Contracts\Database\Eloquent\Castable interface:

1use App\Models\Address;
2 
3protected $casts = [
4 'address' => Address::class,
5];
1use App\Models\Address;
2 
3protected $casts = [
4 'address' => Address::class,
5];

Objects that implement the Castable interface must define a castUsing method that returns the class name of the custom caster class that is responsible for casting to and from the Castable class:

1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Contracts\Database\Eloquent\Castable;
6use App\Casts\Address as AddressCast;
7 
8class Address implements Castable
9{
10 /**
11 * Get the name of the caster class to use when casting from / to this cast target.
12 *
13 * @param array $arguments
14 * @return string
15 */
16 public static function castUsing(array $arguments)
17 {
18 return AddressCast::class;
19 }
20}
1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Contracts\Database\Eloquent\Castable;
6use App\Casts\Address as AddressCast;
7 
8class Address implements Castable
9{
10 /**
11 * Get the name of the caster class to use when casting from / to this cast target.
12 *
13 * @param array $arguments
14 * @return string
15 */
16 public static function castUsing(array $arguments)
17 {
18 return AddressCast::class;
19 }
20}

When using Castable classes, you may still provide arguments in the $casts definition. The arguments will be passed to the castUsing method:

1use App\Models\Address;
2 
3protected $casts = [
4 'address' => Address::class.':argument',
5];
1use App\Models\Address;
2 
3protected $casts = [
4 'address' => Address::class.':argument',
5];

Castables & Anonymous Cast Classes

By combining "castables" with PHP's anonymous classes, you may define a value object and its casting logic as a single castable object. To accomplish this, return an anonymous class from your value object's castUsing method. The anonymous class should implement the CastsAttributes interface:

1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Contracts\Database\Eloquent\Castable;
6use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
7 
8class Address implements Castable
9{
10 // ...
11 
12 /**
13 * Get the caster class to use when casting from / to this cast target.
14 *
15 * @param array $arguments
16 * @return object|string
17 */
18 public static function castUsing(array $arguments)
19 {
20 return new class implements CastsAttributes
21 {
22 public function get($model, $key, $value, $attributes)
23 {
24 return new Address(
25 $attributes['address_line_one'],
26 $attributes['address_line_two']
27 );
28 }
29 
30 public function set($model, $key, $value, $attributes)
31 {
32 return [
33 'address_line_one' => $value->lineOne,
34 'address_line_two' => $value->lineTwo,
35 ];
36 }
37 };
38 }
39}
1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Contracts\Database\Eloquent\Castable;
6use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
7 
8class Address implements Castable
9{
10 // ...
11 
12 /**
13 * Get the caster class to use when casting from / to this cast target.
14 *
15 * @param array $arguments
16 * @return object|string
17 */
18 public static function castUsing(array $arguments)
19 {
20 return new class implements CastsAttributes
21 {
22 public function get($model, $key, $value, $attributes)
23 {
24 return new Address(
25 $attributes['address_line_one'],
26 $attributes['address_line_two']
27 );
28 }
29 
30 public function set($model, $key, $value, $attributes)
31 {
32 return [
33 'address_line_one' => $value->lineOne,
34 'address_line_two' => $value->lineTwo,
35 ];
36 }
37 };
38 }
39}

Comments

No Comments Yet

“Laravel” is a Trademark of Taylor Otwell.
The source documentation is released under MIT license. See laravel/docs on GitHub for details.
The translated documentations are released under MIT license. See cornch/laravel-docs-l10n on GitHub for details.