Support the ongoing development of Laravel.io →
posted 7 years ago
Eloquent

This code:

$translation = Translation::where('language_id', 2)
            ->whereNotNull('data->navigation_login')
            ->select('data->navigation_login as navigation_login')
            ->first()
            ->toArray();
dd($translation);

Produce 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 aboe 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 a snippet from the model:

...
class Translation extends Model {

    protected $casts = [
        'data' => 'array',
    ];
...

Here is a snippet from the schema:

...
$table->json('data')->nullable();
...

Here is the row from the database:

{"navigation_login": "Login", "navigation_order": "Order", "navigation_registration": "Sign up"}
Last updated 3 years ago.
0

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"))
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.