Kike GM Kike GM - 3 months ago 12
JSON Question

How to access a nested field in json with Laravel?

Hello I need to access to a nested field within a json file. I am using Laravel 5 and I have this in controller:

public function getLanguages($id){
$user=User::find($id);

if (!$user)
{
return response()->json(['errors'=>array(['code'=>404,'message'=>'No se encuentra un usuario con ese código.'])],404);
}

return Response::make(json_encode($user->languages), 200)->header('Content-Type', 'application/json');

}


This is the output:

[
{
"id": 1,
"name": "Español",
"pivot": {
"id_user": 1,
"id_language": 1
}
},
{
"id": 2,
"name": "Inglés",
"pivot": {
"id_user": 1,
"id_language": 2
}
},
{
"id": 3,
"name": "Alemán",
"pivot": {
"id_user": 1,
"id_language": 3
}
}
]


I want to access to the name of languages that a user has, how can I do that? This is a many to many relationship between User and Language, is better access to the languages trough the User model? or access from the pivot table?

Thanks.

Answer

Try This

        $user       =   User::find($id)->languages->toArray();
        $languages  =   array_column($user, 'name');  

        return Response::make(json_encode($languages), 200)->header('Content-Type', 'application/json');
Comments