Introduction

You will frequently need to transform your models and relationships to arrays or JSON while developing APIs using OstrojS. Eloquent offers simple ways to do these transformations and lets you choose which properties appear in the serialised representation of your models.

Serializing Models & Collections

Serializing To Arrays

Use the toJson function to turn a model and its loaded relationships into an array. All attributes and all relations (even the relations of relations) will be transformed to arrays because this approach is recursive:

let user = await User.with('roles').first();
return user.toJson();

Although a model's relationships cannot be converted to an array using the attributesToArray method:

let user = await User.first();
return user.attributesToJson();

By using the toArray method on the collection instance, you can easily turn whole collections of models into arrays.

let users = await User.all();
return users.toArray();

Serializing To JSON

Use the toJson function to convert a model to JSON. The toJson function is recursive, much as the toArray method, thus all attributes and relations will be converted to JSON. You can also provide any NodeJS-supported JSON encoding settings, such as:

let user = await User.first();
return user.toJson();

Hiding Attributes From JSON

You might occasionally want to restrict the characteristics that are contained in the array or JSON representation of your model, such as passwords. To accomplish this, give your model a $hidden attribute. The array of the $hidden property's attributes will not be included in the serialised form of your model for the following attributes:

const Model = require('@ostro/database/eloquent/model')
class User extends Model {
   
   $hidden = ['password'];
}
module.exports = User

Alternately, you may provide a "allow list" of attributes to be included in your model's array and JSON representation using the visible property. When the model is transformed into an array or JSON, any properties that are absent from the $visible array are hidden:

const Model = require('@ostro/database/eloquent/model')
class User extends Model {
   
   $visible = ['first_name', 'last_name'];
}
module.exports = User

Appending Values To JSON

On sometimes, you might want to add properties when converting models to arrays or JSON that don't have equivalent columns in your database. Create an accessor for the value first, then do this:

Add the attribute name to your model's appends property after establishing the accessor. Even though the accessor's NodeJS function is declared using "camel case," attribute names are commonly addressed using their "snake case" serialised representation:

const Model = require('@ostro/database/eloquent/model')
class User extends Model {
   
$appends = {'is_admin':true};
}
module.exports = User