Laravel Tutorials

Working with JSON Attributes Using Laravel's Array Casts

Published
Working with JSON Attributes Using Laravel's Array Casts image

Laravel provides AsArrayObject and AsCollection casts to handle complex JSON attributes more effectively, enabling intuitive manipulation of nested data structures.

<?php

use Illuminate\Database\Eloquent\Casts\AsArrayObject;
use Illuminate\Database\Eloquent\Casts\AsCollection;

class User extends Model
{
    protected $casts = [
        'settings' => AsArrayObject::class,
        'tags' => AsCollection::class
    ];
}

Let's explore a complete example of a Product model that uses JSON attributes to manage specifications and variants:

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\AsArrayObject;
use Illuminate\Database\Eloquent\Casts\AsCollection;

class Product extends Model
{
    protected $fillable = ['name', 'specs', 'variants'];
    protected $casts = [
        'specs' => AsArrayObject::class,
        'variants' => AsCollection::class,
    ];
}

// Migration for this model would look like:
public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->json('specs');
        $table->json('variants');
        $table->timestamps();
    });
}

// Usage example:
$product = Product::create([
    'name' => 'Gaming Laptop',
    'specs' => [
        'processor' => 'Intel i7',
        'ram' => '16GB',
        'storage' => [
            'primary' => '512GB SSD',
            'secondary' => '1TB HDD'
        ]
    ],
    'variants' => [
        ['color' => 'Black', 'price' => 999],
        ['color' => 'Silver', 'price' => 1099]
    ]
]);

//
// Update nested specs without any PHP errors
$product->specs['storage']['primary'] = '1TB SSD';
$product->save();
// Use collection methods on variants
$product->variants->push(['color' => 'Red', 'price' => 1199]);
$product->save();
// Filter variants using collection methods
$expensiveVariants = $product->variants->where('price', '>', 1000);

These casts enable seamless manipulation of JSON data while maintaining clean, maintainable code. AsArrayObject provides array-like access, while AsCollection offers Laravel's powerful collection methods.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
Generate Laravel Validation Rules From a JSON Schema image

Generate Laravel Validation Rules From a JSON Schema

Read article
Laravel Suspicious Login: Detect and Block Risky Logins image

Laravel Suspicious Login: Detect and Block Risky Logins

Read article
Decide with Jev: Make Failed AI Requests Safe in Laravel image

Decide with Jev: Make Failed AI Requests Safe in Laravel

Read article
Black Friday: Learn the habits behind AI workflows that work image

Black Friday: Learn the habits behind AI workflows that work

Read article
Laravel Black Friday and Cyber Monday Deals 2026 image

Laravel Black Friday and Cyber Monday Deals 2026

Read article
pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux image

pgjumbo: A PostgreSQL Client for macOS, Windows, and Linux

Read article