Skip to content

Commit

Permalink
[8.x] Add castAsJson method for database assertions (#34302)
Browse files Browse the repository at this point in the history
* add `castAsJson` method for database assertions

database fields of type 'json' cannot be evaluted using strings, they must be cast to a database specific JSON type.

* Update InteractsWithDatabase.php

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
browner12 and taylorotwell committed Sep 14, 2020
1 parent 846d4da commit 18940d5
Showing 1 changed file with 14 additions and 0 deletions.
Expand Up @@ -5,6 +5,7 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Testing\Constraints\CountInDatabase;
use Illuminate\Testing\Constraints\HasInDatabase;
use Illuminate\Testing\Constraints\SoftDeletedInDatabase;
Expand Down Expand Up @@ -118,6 +119,19 @@ protected function isSoftDeletableModel($model)
&& in_array(SoftDeletes::class, class_uses_recursive($model));
}

/**
* Cast a JSON string to a database compatible type.
*
* @param array|string $value
* @return \Illuminate\Database\Query\Expression
*/
public function castAsJson($value)
{
$value = is_array($value) ? json_encode($value) : $value;

return DB::raw("CAST('$value' AS JSON)");
}

/**
* Get the database connection.
*
Expand Down

0 comments on commit 18940d5

Please sign in to comment.