Migrating from FuelPHP to Laravel: problem with one response

304 views Asked by At

i'm migrating an old project from fuel to laravel and i'm having trouble with the response to one of the requests. The issue is, i need the response from laravel to be exactly the same as it was in fuel, because i already have the app in iOS and Android and having the same responses means i only need to change the endpoints. I can't seem to replicate the response here:

  • FuelPHP code and response:

        $belongs = Model_Belong::find('all',array(
            'where'=>array(
                array('id_user',$id_user),
            ),
        ));
    
    return $this->createResponse(200, 'List', $belongs);
    *****RESPONSE****
    {
    "code": 200,
    "message": "List",
    "data": {
        "[1][1]": {
            "id_user": 1,
            "id_group": 1
        },
        "[1][2]": {
            "id_user": 1,
            "id_group": 2
        },
        "[1][3]": {
            "id_user": 1,
            "id_group": 3
        }
    }
    }
    
  • Laravel code and response:

        $belongs = Belong::where('id_user', $id_user)
                    ->get();
    
    return $this->createResponse(200, 'List', $belongs);
    *****RESPONSE*****
    {
    "code": 200,
    "message": "List",
    "data": [
        {
            "id_user": 1,
            "id_group": 1,
        },
        {
            "id_user": 1,
            "id_group": 2,
        },
        {
            "id_user": 1,
            "id_group": 3,
        }
    ]
    }
    

***edit: createResponse() method

    function createResponse($code, $message, $data = [])
{
    if ($data == null) {
       $data = (object)[];
    }
    return response()->json([
        'code' => $code,
        'message' => $message,
        'data' => $data
    ]);

}
1

There are 1 answers

4
Murat Tutumlu On

I think a hacky solution can be done by producing own key by sql and retrieve it by using KeyBy() as following:

Belong::select([
        'id_user',
        'id_group', 
        DB::raw("CONCAT('[', id_user, '][', id_group, ']') as mykey")
    ])
    ->where('id_user', $id_user)
    ->get()
    ->keyBy('mykey');