drz5553
drz5553
2019-07-17 21:24
浏览 80
已采纳

如何在laravel中将数组中属性的JSON字符串值作为JSON数组返回

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条回答 默认 最新

  • dongza5150
    dongza5150 2019-07-17 22:17
    已采纳

    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');
        }
    }
    
    点赞 评论

相关推荐