Search code examples
laravelapihttp-postlaravel-7

Using Http::post to get data from API


I tried to get data from API, when in Postman it's working fine but when i tried it in laravel it return an error

Postman Result

How do i get that data to laravel?

This is from my controller :

$response = Http::post('https://url.id/api/tryout/check', [
                'category_id' => 0,
                'platform' => 'platform',
                'is_unique' => false,
                'chapters' => [
                    'id' => 3,
                    'name' => "Aljabar",
                    'count' => 10,
                ],
        ]);

return $response;

But the code above will return an error :

Trying to access array offset on value of type int

Solution

  • you are passing your chapters data as array of object in your POSTMAN,

    "chapters": [
        {
            "id": 1,
            ..
            ..
        },
        {
            "id": 3,
            ..
            ..
        }
    ]
    

    then its a plain object in your Laravel HTTP request, which throwing an error because you are looping through id, name and count and not through an object containing those key which your loop expects to have

    "chapters": {
        "id": 3,
            ..
            ..
    }
    

    you need this part to be a list of objects

    'chapters' => [
        'id' => 3,
        ..
    ],
    

    should be

    'chapters' => [
        [ 
            'id' => 3,
            ..
        ]
    ],