> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Eloquent serialization

> Learn how to convert Eloquent models to JSON or arrays, control which attributes are shown or hidden, add appended attributes, and customize date formats.

## Introduction

When building APIs with Laravel, you'll often need to convert your models and their relationships to arrays or JSON.
Eloquent includes convenient methods for performing these conversions, as well as controlling which attributes are included in the serialized representation of your models.

<Info>
  For an even more robust way to handle Eloquent model and collection JSON serialization, see the documentation on [Eloquent API resources](./eloquent-resources).
</Info>

## Models and arrays

### Serializing to arrays

To convert a model and its loaded [relationships](./eloquent-relationships) to an array, use the `toArray` method.
This method is recursive, so all attributes and all relationships (including the relationships' relationships) will be converted to arrays.

```php theme={null}
use App\Models\User;

$user = User::with('roles')->first();

return $user->toArray();
```

The `attributesToArray` method may be used to convert a model's attributes to an array without its relationships.

```php theme={null}
$user = User::first();

return $user->attributesToArray();
```

You may also convert entire collections of models to arrays by calling the `toArray` method on the collection instance.

```php theme={null}
$users = User::all();

return $users->toArray();
```

### Serializing to JSON

To convert a model to JSON, you should use the `toJson` method.
Like `toArray`, the `toJson` method is recursive, so all attributes and relationships will be converted to JSON.
You may also specify any [JSON encoding options that are supported by PHP](https://secure.php.net/manual/en/function.json-encode.php).

```php theme={null}
use App\Models\User;

$user = User::find(1);

return $user->toJson();

return $user->toJson(JSON_PRETTY_PRINT);
```

Alternatively, you may cast a model or collection to a string, which will automatically call the `toJson` method on the model or collection.

```php theme={null}
return (string) User::find(1);
```

Since models and collections are converted to JSON when cast to a string, you can return Eloquent objects directly from your application's routes or controllers.
Laravel will automatically serialize your Eloquent models and collections to JSON when they are returned from routes or controllers.

```php theme={null}
Route::get('/users', function () {
    return User::all();
});
```

#### Relationships

When an Eloquent model is converted to JSON, its loaded relationships will automatically be included as attributes on the JSON object.
Also, though Eloquent relationship methods are defined using "camelCase" method names, a relationship's JSON attribute will be "snake\_case".

## Controlling attribute visibility

### Hiding attributes

Sometimes you may wish to limit the attributes, such as passwords, that are included in your model's array or JSON representation.
To do so, use the `Hidden` attribute on your model.
Attributes that are listed in the `Hidden` attribute will not be included in the serialized representation of your model.

```php theme={null}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Model;

#[Hidden(['password'])]
class User extends Model
{
    // ...
}
```

<Info>
  To hide relationships, add the relationship's method name to your Eloquent model's Hidden attribute.
</Info>

### Making attributes visible

You may also use the `Visible` attribute to define an "allow list" of attributes that should be included in your model's array and JSON representation.
All attributes that are not present in the `Visible` attribute will be hidden when the model is converted to an array or JSON.

```php theme={null}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Attributes\Visible;
use Illuminate\Database\Eloquent\Model;

#[Visible(['first_name', 'last_name'])]
class User extends Model
{
    // ...
}
```

### Temporarily modifying attribute visibility

If you would like to make some typically hidden attributes visible on a given model instance, you may use the `makeVisible` or `mergeVisible` method.
The `makeVisible` method returns the model instance.

```php theme={null}
return $user->makeVisible('attribute')->toArray();

return $user->mergeVisible(['name', 'email'])->toArray();
```

Likewise, if you would like to hide some attributes that are typically visible, you may use the `makeHidden` or `mergeHidden` method.

```php theme={null}
return $user->makeHidden('attribute')->toArray();

return $user->mergeHidden(['name', 'email'])->toArray();
```

If you wish to temporarily override all of the visible or hidden attributes, you may use the `setVisible` and `setHidden` methods respectively.

```php theme={null}
return $user->setVisible(['id', 'name'])->toArray();

return $user->setHidden(['email', 'password', 'remember_token'])->toArray();
```

## Appending values to JSON

Occasionally, when converting models to arrays or JSON, you may wish to add attributes that do not have a corresponding column in your database.
To do so, first define an [accessor](./eloquent-mutators) for the value.

```php theme={null}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Determine if the user is an administrator.
     */
    protected function isAdmin(): Attribute
    {
        return new Attribute(
            get: fn () => 'yes',
        );
    }
}
```

If you would like the accessor to always be appended to your model's array and JSON representations, you may use the `Appends` attribute on your model.
Note that the accessor's PHP method is defined using "camelCase", while the attribute name is typically referenced using its "snake\_case" serialized representation.

```php theme={null}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Attributes\Appends;
use Illuminate\Database\Eloquent\Model;

#[Appends(['is_admin'])]
class User extends Model
{
    // ...
}
```

Once the attribute has been added to the `appends` list, it will be included in both the model's array and JSON representations.
Attributes in the `appends` array will also respect the `visible` and `hidden` settings configured on the model.

### Appending at runtime

At runtime, you may instruct a model instance to append additional attributes using the `append` or `mergeAppends` method.
You can also use the `setAppends` method to override the entire array of appended properties for a given model instance.

```php theme={null}
return $user->append('is_admin')->toArray();

return $user->mergeAppends(['is_admin', 'status'])->toArray();

return $user->setAppends(['is_admin'])->toArray();
```

To remove all appended properties from the model, use the `withoutAppends` method.

```php theme={null}
return $user->withoutAppends()->toArray();
```

## Date serialization

### Customizing the default date format

You may customize the default serialization format by overriding the `serializeDate` method.
This method does not affect how your dates are formatted for storage in the database.

```php theme={null}
/**
 * Prepare a date for array / JSON serialization.
 */
protected function serializeDate(DateTimeInterface $date): string
{
    return $date->format('Y-m-d');
}
```

### Customizing the date format per attribute

You may customize the serialization format of individual Eloquent date attributes by specifying the date format in the model's [cast declarations](./eloquent-mutators#attribute-casting).

```php theme={null}
protected function casts(): array
{
    return [
        'birthday' => 'date:Y-m-d',
        'joined_at' => 'datetime:Y-m-d H:00',
    ];
}
```


## Related topics

- [Eloquent collections](/en/eloquent-collections.md)
- [Eloquent accessors, mutators, and casting](/en/eloquent-mutators.md)
- [PHP Attributes](/en/advanced/php-attributes.md)
- [Upgrade guide: Laravel 12 to 13](/en/blog/upgrade-12-to-13.md)
- [Laravel 13 new features overview](/en/blog/laravel-13-new-features.md)
