Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      May 16, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      May 16, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      May 16, 2025

      How To Prevent WordPress SQL Injection Attacks

      May 16, 2025

      Microsoft has closed its “Experience Center” store in Sydney, Australia — as it ramps up a continued digital growth campaign

      May 16, 2025

      Bing Search APIs to be “decommissioned completely” as Microsoft urges developers to use its Azure agentic AI alternative

      May 16, 2025

      Microsoft might kill the Surface Laptop Studio as production is quietly halted

      May 16, 2025

      Minecraft licensing robbed us of this controversial NFL schedule release video

      May 16, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      The power of generators

      May 16, 2025
      Recent

      The power of generators

      May 16, 2025

      Simplify Factory Associations with Laravel’s UseFactory Attribute

      May 16, 2025

      This Week in Laravel: React Native, PhpStorm Junie, and more

      May 16, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Microsoft has closed its “Experience Center” store in Sydney, Australia — as it ramps up a continued digital growth campaign

      May 16, 2025
      Recent

      Microsoft has closed its “Experience Center” store in Sydney, Australia — as it ramps up a continued digital growth campaign

      May 16, 2025

      Bing Search APIs to be “decommissioned completely” as Microsoft urges developers to use its Azure agentic AI alternative

      May 16, 2025

      Microsoft might kill the Surface Laptop Studio as production is quietly halted

      May 16, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Working with JSON Attributes Using Laravel’s Array Casts

    Working with JSON Attributes Using Laravel’s Array Casts

    December 23, 2024

    Working with JSON Attributes Using Laravel's Array Casts

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

    <?php
    
    use IlluminateDatabaseEloquentCastsAsArrayObject;
    use IlluminateDatabaseEloquentCastsAsCollection;
    
    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 AppModels;
    
    use IlluminateDatabaseEloquentModel;
    use IlluminateDatabaseEloquentCastsAsArrayObject;
    use IlluminateDatabaseEloquentCastsAsCollection;
    
    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.


    The post Working with JSON Attributes Using Laravel’s Array Casts appeared first on Laravel News.

    Join the Laravel Newsletter to get all the latest
    Laravel articles like this directly in your inbox.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleThe Design Leader Dilemma
    Next Article Token Forge

    Related Posts

    Security

    Nmap 7.96 Launches with Lightning-Fast DNS and 612 Scripts

    May 17, 2025
    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-4831 – TOTOLINK HTTP POST Request Handler Buffer Overflow Vulnerability

    May 17, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    Hire Overseas

    Web Development

    Enhancing AI Validation with Causal Chambers: Bridging Data Gaps in Machine Learning and Statistics with Controlled Environments

    Development

    OvrC Platform Vulnerabilities Expose IoT Devices to Remote Attacks and Code Execution

    Development

    Lesser known Windows 11 features for power users

    Operating Systems
    Hostinger

    Highlights

    Development

    This AI Paper Introduces HARec: A Hyperbolic Framework for Balancing Exploration and Exploitation in Recommender Systems

    November 26, 2024

    Recommender systems are essential in modern digital platforms, enabling personalized user experiences by predicting preferences…

    This $449 Lenovo convertible laptop gets up to 13 hours of battery life

    April 1, 2025

    Install Sitecore Hotfixes on Azure PaaS with Azure DevOps Pipeline

    February 17, 2025

    How DNS Works: A Guide to Understanding the Internet’s Address Book

    May 14, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.