1

I have this nested json in my database

 {

"skills":{
    "skill1":{
        "description":"deal 100 damage",
        "cost":2,
        "name":"basic skill"
    },
        "skill2":{
        "description":"deal 900 damage",
        "cost":1,
        "name":"special skill"
    }
}
}

but when i get this json from my database , its returning a string (image1)

image1 im using laravel to get the data from the database .

 public function list(){
        $data = Cd::all();
        return $data;  
  }

and i want this json to be like in postman preview (image2), an array so i can access its properties ,

example: after a foreach I can access "skill1->description" , cost ,etc.

How can i do that ?

image2

1 Answer 1

1

in your Cd Model you should cast your 'skills' attribute:

class Cd extends Model 
{
 protected $casts = ['skills'=>'array'];
.... 
}

by using '$casts' your model will automatically convert the json field into string instead of pure string

more about array & json casting in:

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

Sign up to request clarification or add additional context in comments.

2 Comments

will try !, should i migrate after doing this ?
no, this code will make the wanted result without the need to migrate

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.