This code:
$translation = Translation::where('language_id', 2)
->whereNotNull('data->navigation_login')
->select('data->navigation_login as navigation_login')
->first()
->toArray();
dd($translation);
Produces this result:
array(1) {["navigation_login"]=> string(7) ""Login"" }
The problem is the extra double quote arround the login string: ""Login""
How can I eliminate this?
If I run the above code without select:
$translation = Translation::where('language_id', 2)
->whereNotNull('data->navigation_login')
->first()
->toArray();
dd($translation);
No double quotes:
["data"]=>
array(3) {
["navigation_login"]=>
string(5) "Login"
["navigation_order"]=>
string(5) "Order"
["navigation_registration"]=>
string(7) "Sign up"
}
Here is the model detail:
...
class Translation extends Model {
protected $casts = [
'data' => 'array',
];
...
Here is the schema detail:
...
$table->json('data')->nullable();
...
Finally the solution:
MySQL 5.7.13 and later
Using the unquoting extraction operator ->>
->select('data->>navigation_login as navigation_login')
Or older mysql version 5.7 < MYSQL < 5.7.13
->select(\DB::raw("JSON_UNQUOTE(JSON_EXTRACT(data, '$.navigation_login')) as navigation_login"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With