If you don't want nested data then you need to use a join.
but, be prepared to see duplicate engagements if there can be multiple questions.
is it a 1:1 relationship or 1:many ?
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello, I am wanting to change the format of a response that I am getting when I do the following in my controller
public function questionindex($client_id)
{
$engagements = Engagement::where('client_id', $client_id)->with('questions')->get();
foreach($engagements as $engagement) {
echo($engagement->questions);
}
return response($engagements);
}
Currently the response is in a unusable format. I would like for it to be a single array of objects. Any suggestions on helpers I can use to make this happen?
here is what the I currently get back
[{"id":32,"engagement_id":63,"question":"Just testing out the workflow?","answer":null,"answered":0,"created_at":"2018-10-05 21:33:08"}][{"id":63,"client_id":10,"return_type":"1040","year":"2018","assigned_to":"Lissa","status":"Recieved","done":0,"created_at":"2018-10-05 21:32:47","updated_at":"2018-10-05 21:32:47","questions":[{"id":32,"engagement_id":63,"question":"Just testing out the workflow?","answer":null,"answered":0,"created_at":"2018-10-05 21:33:08"}]}]
This is what I would like it to be
[
{
"id":32,
"engagement_id":63,
"question":"Just testing out the workflow?",
"answer":null,
"answered":0,
"created_at":"2018-10-05 21:33:08"
}
{
"id":32,
"engagement_id":63,
"question":"Just testing out the workflow?",
"answer":null,
"answered":0,
"created_at":"2018-10-05 21:33:08"
}
{
"id":32,
"engagement_id":63,
"question":"Just testing out the workflow?",
"answer":null,
"answered":0,
"created_at":"2018-10-05 21:33:08"
}
]
I used this
public function questionindex($client_id)
{
$engagements = Engagement::where('client_id', $client_id)->with('questions')->get();
$questions = $engagements->pluck('questions');
$flatten = $questions->flatten(1);
return response($flatten);
}
it returns a response of questions only like so only belonging to client
[
{
"id": 28,
"engagement_id": 57,
"question": "This is a new question??",
"answer": "<p>Why isnt this working?</p>",
"answered": 1,
"created_at": "2018-10-05 18:48:48"
},
{
"id": 36,
"engagement_id": 57,
"question": "What happens if add a new questions?",
"answer": "<p>But this doesnot work</p>",
"answered": 1,
"created_at": "2018-10-06 14:45:29"
},
{
"id": 37,
"engagement_id": 65,
"question": "Just adding a new question?",
"answer": "<p>So does this work now to?</p>",
"answered": 1,
"created_at": "2018-10-06 14:50:10"
}
]
One array of objects.
Please or to participate in this conversation.