During testing with the Laravel framework, you often want to check if a database contains a record which contains a JSON string (especially if you are using JSON columns in your database).

You might have found that using json_encode doesn't work:

<?php

$this->assertDatabaseHas(
    'backups',
    [
        'tries'        => 1,
        'status'       => BackupStatus::SUCCESS,
        'message'      => null,
        'document_id'  => $document->id,
        'destinations' => json_encode(['a', 'b']),
    ]
);

Due to a difference in the way the JSON string is encoded, the check will fail (.

To fix it, you simply need to use $this->castAsJson instead (API documentation can be found here:

<?php

$this->assertDatabaseHas(
    'backups',
    [
        'tries'        => 1,
        'status'       => BackupStatus::SUCCESS,
        'message'      => null,
        'document_id'  => $document->id,
        'destinations' => $this->castAsJson(['a', 'b']),
    ]
);

Related Posts

  • Using macros with Laravel
  • Laravel Service Provider in Simple English
  • Customising lazy-loading prevention in Laravel
  • Optimising large whereIn queries in Laravel
  • The giveConfig function in Laravel