首页 > 解决方案 > How to convert a mysql json field to a javascript Object with laravel?

问题描述

I'm using laravel with eloquent and a mysql database.

There is a JSON field in my database:

class CreateJogoDetalhesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tableX', function (Blueprint $table) {
            $table->increments('id');
            [... others ...]
            $table->json('numbers');
    }
[...]

When I retrieve the data on my model/api route:

Route::middleware('cors:api')->get('/MYROUTE', function (Request $request) {
    $resource= Tablex::with('tb1','tb2','tb3')->get();
    return $resource->toJson();
});

My mysql json field comes with a string format:

tableX": {
      "id": 1,
      "name": "foo",
      "values": "{\"6\": 3.5, \"7\": 24.5, \"8\": 24.5, \"9\": 24.5, \"10\": 24.5, \"11\": 24.5, \"12\": 24.5, \"13\": 24.5, \"14\": 24.5, \"15\": 24.5}",
    },

But I need them on this format:

"tableX": {
      "id": 1,
      "name": "foo",
      "values": {
        "6": 3.5,
        "7": 24.5,
        "8": 24.5,
        "9": 24.5,
        "10": 24.5,
        "11": 24.5,
        "12": 24.5,
        "13": 24.5,
        "14": 24.5,
        "15": 24.5
      },

How can I ask to laravel catch the data on this format?

标签: phpmysqllaravel

解决方案


The array cast type is particularly useful when working with columns that are stored as serialized JSON. For example, if your database has a JSON or TEXT field type that contains serialized JSON, adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model:

class User extends Model
{
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'values' => 'array',
    ];
}

https://laravel.com/docs/5.7/eloquent-mutators#array-and-json-casting

This will convert it to an array on the PHP side and will properly include the JSON data when Laravel serializes the model.


推荐阅读