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»Asserting a JSON Response Structure in Laravel

    Asserting a JSON Response Structure in Laravel

    June 18, 2024

    When writing tests for API responses in Laravel, it can be useful to validate the structure of the response. Laravel has the fluent assertJson() method, which you can use to verify JSON values in a given test response:

    it(‘Returns Arizona sports teams’, function () {
    $this->get(‘api/teams/arizona’)
    ->assertJson(function (AssertableJson $json) {
    $json->has(‘teams’, 3);
    $json->has(‘teams.0’, function (AssertableJson $json) {
    $json
    ->where(‘name’, ‘Phoenix Suns’)
    ->etc();
    });
    });
    });

    Given the above test, here’s a static example of the JSON data:

    {
    “teams”: [
    {
    “name”: “Phoenix Suns”,
    “sport”: “Basketball”
    },
    {
    “name”: “Arizona Cardinals”,
    “sport”: “Football”
    },
    {
    “name”: “Arizona Diamondbacks”,
    “sport”: “Baseball”
    }
    ]
    }

    Our test validates that three teams are listed in Arizona and that the name property exists on the first record. That’s excellent for validating the actual values to sample the response using the powerful JSON assertion APIs in Laravel. To complement those assertions, we can also validate the general structure of the whole response:

    $response->assertJsonStructure([
    ‘teams’ => [
    ‘*’ => [‘name’, ‘sport’],
    ],
    ]);

    One caveat to the assertJsonStucture() assertion: if we add a new key in the future, this test will continue to pass. If you require more exactness, you might need to reach for the assertExactJson(). For just generalizing a JSON structure to ensure specific properties exist in the response, assertJsonStructure() can give you confidence that the entire structure contains properties you expect.

    If you need more extensive assertions around the structure of the JSON, you might also want to reach for whereType() and whereAllType() assertions. Given our earlier example, you could validate the types in your JSON responses using the following:

    $response->assertJson(function (AssertableJson $json) {
    $json->has(‘teams’, 3);
    $json->has(‘teams.0’, function (AssertableJson $json) {
    $json->whereAllType([
    ‘name’ => ‘string’,
    ‘sport’ => ‘string’,
    ]);
    });
    });

    Using whereAllType requires us to define types for each and every key in the teams item, unless you use the above with ->etc():

    $json->whereAllType([
    ‘name’ => ‘string’,
    // ‘sport’ => ‘string’,
    ])->etc();

    As mentioned, the above code doesn’t assert the whole response and assumes the other teams have the same structure. You could assert each team in the array, and even use Eloquent factory data to validate the response values match. Typically, combining the above assertions will ensure you have the expected JSON response shape, and you can mix in more complicated assertions where needed. See the Laravel Documentation for more examples and useful JSON assertions.

    The post Asserting a JSON Response Structure in Laravel 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 

    Hostinger
    Facebook Twitter Reddit Email Copy Link
    Previous ArticleJeffrey’s Larabits: Laravel Socialite and Github Authentication Workshop
    Next Article Efficient Record Assignment: Assign Records to Queues with Salesforce Flows

    Related Posts

    Security

    Nmap 7.96 Launches with Lightning-Fast DNS and 612 Scripts

    May 17, 2025
    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-48187 – RAGFlow Authentication Bypass

    May 17, 2025
    Leave A Reply Cancel Reply

    Hostinger

    Continue Reading

    Designing for people: What architecture can learn from UX

    Web Development

    CERT-UA Warns of Escalating Cyberattacks Targeting Ukraine’s Defense Sector with DarkCrystal RAT

    Development

    CVE-2025-4712 – Campcodes Sales and Inventory System SQL Injection Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    CodeSOD: Building Blocks

    Development

    Highlights

    7 strategic insights business and IT leaders need for AI transformation in 2025

    April 11, 2025

    Enterprise Connect 2025 highlighted the necessity of practical and scalable tech solutions to unlock new…

    Tornare a sviluppare “e basta” sarà mai possibile? Probabilmente no, ma l’AI potrebbe aiutare, almeno secondo GitLab

    December 25, 2024

    Weekly JavaScript Roundup: Friday Links 14, January 3, 2025

    January 3, 2025

    One of my favorite EcoFlow portable power stations is 44% off on Amazon ahead of July 4

    July 1, 2024
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

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