简体   繁体   中英

How to return JSON string value of property in array as JSON array in laravel

I store JSON string in a column of MySQL table. When I try to return that column data as php/json array via API it's yet as a string.

Here is my code which returns an array of questions and in every question object, I've options array as JSON stringify. But, when it returns I don't want options as stringified.

    public function getQuestions($id, Request $request)
    {
        // return $id;

        $questions = Question::where('quiz_id', $id)->orderByRaw("RAND()")->get();
        $questions->makeHidden(['ans']);
        // $questions->toJson(['options']);

        // $questions['options'] = json_encode(questions['options']);
        return $questions;
    }

It returns like this.

[
    {
        "id": 100000008,
        "quiz_id": 10000,
        "title": "কোন বানানটি সঠিক?",
        "options": "[\"কলসি\",\"কলসই\",\"কলশি\",\"কলশী\"]",
        "answer": 1
    },
    {
        "id": 100000009,
        "quiz_id": 10000,
        "title": "কোন বানানটি সঠিক?",
        "options": "[\"ঠোট\",\"ঠোঁট\",\"থট\",\"কোনটি নয়\"]",
        "answer": 2
    }
]

But I want like this:

[
    {
        "id": 100000008,
        "quiz_id": 10000,
        "title": "কোন বানানটি সঠিক?",
        "options": ["কলসি","কলসই","কলশি","কলশী"],
        "answer": 1
    },
    {
        "id": 100000009,
        "quiz_id": 10000,
        "title": "কোন বানানটি সঠিক?",
        "options": ["ঠোট","ঠোঁট","থট","কোনটি নয়"],
        "answer": 2
    }
]

I just added $casts convert the string to array

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Question extends Model
{
    protected $table = 'question';

    protected $fillable = [
        'quiz_id',
        'title',
        'opt1',
        'opt2',
        'opt3',
        'opt4',
        'ans',
        'options',
        'answer'
    ];

    protected $casts = [
        'options' => 'array',
    ];

    public function quiz()
    {
        return $this->belongsTo('App\Quize', 'quiz_id' , 'id');
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM