Laravel Tutorials

Quick Tip: Unit Testing JSON Columns in Laravel

Published
Quick Tip: Unit Testing JSON Columns in Laravel image

You may know that you can query against JSON columns using the column->key syntax in Laravel, but I recently learned you can use the same syntax in your tests when asserting that the database has certain data!

Query Example

FormElement::where('rules->required', null)->get();

Testing Example

/** @test */
public method a_form_element_can_be_stored
{
// Do some stuff...
 
$this->assertDatabaseHas('form_elements', [
'rules->required' => null,
]);
}

Check out all our posts on testing with Laravel.

Jason Beggs photo

TALL stack (Tailwind CSS, Alpine.js, Laravel, and Livewire) consultant and owner of designtotailwind.com.

Sponsored

masteringlaravel logo
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article