Use casts to automatically parse/serialize JSON on read and write:
export default class Product extends Model { static table = 'products'; static casts = { metadata: 'json', // parsed on read, serialized on write tags: 'array', // same as json but semantically an array settings: 'object', // same as json but semantically a key-value map };}
Now you work with native JS objects/arrays — no JSON.parse() needed:
// Products with more than 3 tagsconst richlyTagged = await Product.query() .whereJsonLength('tags', '>', 3) .get();// Products with exactly 1 tagconst singleTag = await Product.query() .whereJsonLength('tags', '=', 1) .get();
whereJsonContains and whereJsonLength work across MySQL, PostgreSQL, and SQLite. The correct SQL function is chosen automatically based on your database driver.
// casts/PriceCast.jsexport default class PriceCast { // Called when reading from database (cents → dollars) get(value) { return value !== null ? (value / 100).toFixed(2) : null; } // Called when writing to database (dollars → cents) set(value) { return Math.round(parseFloat(value) * 100); }}
import PriceCast from '../casts/PriceCast.js';export default class Product extends Model { static casts = { price: PriceCast, };}
const product = await Product.create({ name: 'Widget', price: '9.99' });// Stored as 999 in the databaseproduct.price; // '9.99' (converted back on read)
Real-World Example: User Preferences
export default class User extends Model { static casts = { preferences: 'json', notification_channels: 'array', };}