Skip to content

Commit 18940d5

Browse files
[8.x] Add castAsJson method for database assertions (#34302)
* 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 <[email protected]>
1 parent 846d4da commit 18940d5

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use Illuminate\Database\Eloquent\Model;
66
use Illuminate\Database\Eloquent\SoftDeletes;
77
use Illuminate\Support\Arr;
8+
use Illuminate\Support\Facades\DB;
89
use Illuminate\Testing\Constraints\CountInDatabase;
910
use Illuminate\Testing\Constraints\HasInDatabase;
1011
use Illuminate\Testing\Constraints\SoftDeletedInDatabase;
@@ -118,6 +119,19 @@ protected function isSoftDeletableModel($model)
118119
&& in_array(SoftDeletes::class, class_uses_recursive($model));
119120
}
120121

122+
/**
123+
* Cast a JSON string to a database compatible type.
124+
*
125+
* @param array|string $value
126+
* @return \Illuminate\Database\Query\Expression
127+
*/
128+
public function castAsJson($value)
129+
{
130+
$value = is_array($value) ? json_encode($value) : $value;
131+
132+
return DB::raw("CAST('$value' AS JSON)");
133+
}
134+
121135
/**
122136
* Get the database connection.
123137
*

0 commit comments

Comments
 (0)