Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel eloquent JSON field, selecting attribute produce extra double quote

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();
...
like image 919
robcaa Avatar asked Oct 29 '22 22:10

robcaa


1 Answers

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

like image 60
robcaa Avatar answered Nov 09 '22 12:11

robcaa