-
Notifications
You must be signed in to change notification settings - Fork 11.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[8.x] Add castAsJson
method for database assertions
#34302
Conversation
database fields of type 'json' cannot be evaluted using strings, they must be cast to a database specific JSON type.
castAsJson
method for database assertionscastAsJson
method for database assertions
It feels like this should be more automatic maybe? |
that would be nice, but I'm not sure that would be reasonably possible. you'd have to know/query the field type prior. even if you had the Model, you couldn't base it off that, because some people use the 'json' cast, but still use a 'longtext' or similar as the database type, and we don't need to do this for those field types. If you have a thought on how to accomplish this, I'm definitely open to it. |
If you are calling the function i.e. - $this->castAsJson(json_encode(['web slinging', 'spidey-sense', 'sticky feet'])),
+ $this->castAsJson(['web slinging', 'spidey-sense', 'sticky feet']), And then have the function do the |
PHP JSON encoding is different than database type casting. I'm passing in an array, so first that needs to be encoded as a string, and then that string needs to be cast to JSON in the database query. |
Sorry - I was not very clear - I meant then do the json_encoding in the other function. Something like this: public function castAsJson($value)
{
+ $value = json_encode($value);
return DB::raw("CAST('$value' AS JSON)");
} |
Ah, I see. I go back and forth on if that's the responsibility of this method. I'm not sure if there'd be a scenario where someone already has a value as JSON, so then they would need to decode it prior to passing it to the function, so it doesn't get double encoded. Honestly, I could go either way on this, so would be open to hearing other people's opinions. |
What's still missing here is escaping. |
Refs #37619 |
database fields of type 'json' cannot be evaluated using strings, they must be cast to a database specific JSON type.