2

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
    }
]

1 Answer 1

5

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');
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.