boldstar
113
27
Laravel

How to change format of response data?

Posted 5 months ago by boldstar

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

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.