Skip to content
Advertisement

Getting rid of numbers in a json response ( LARAVEL 9 )

i’m having some problems with my json response.

When I make an api call from a user (id:1) it returns the response well, but if i change the user (f.e id:2) it returns it with some identifiers on it. Any idea?

Response from id:1

{
    "data": [
        {
            "id": 1,
            "matricula": "222555999C",
            "capacidad": "220",
            "created_at": "2022-04-06T09:52:39.000000Z",
            "updated_at": "2022-04-06T09:52:39.000000Z",
            "deleted_at": null,
            "transportista": 1
        }
    ]
}

Response from id:2

{
    "data": {
        "3"(<--- this is the problem): {
            "id": 9,
            "matricula": "HYK 2024",
            "capacidad": "100",
            "created_at": "2022-04-08T15:12:22.000000Z",
            "updated_at": "2022-04-08T15:12:22.000000Z",
            "deleted_at": null,
            "transportista": 2
        }
    }
}

Thanks!

EDIT 1

This is how I am getting the response:

public function getCamiones(Request $request) {
    $id = $request->get('id');
    $camiones = Camiones::all()->where('transportista',$id);
    return response()->json([
        'data' => $camiones,
    ]);
}

Advertisement

Answer

Right now, you’re getting all of the results, then filtering the collection returned, instead of having the database do the work for you. Instead, grab only a single row.

$camiones = Camiones::where('transportista', $id)->first();

To get all the rows that match, then you need

$camiones = Camiones::where('transportista', $id)->get();
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement