Steven Grant
Steven Grant

Reputation: 1325

access data array in JSON with Laravel & Guzzle

I'm trying to retrieve data from an API that gives a response like so:

{
   "data":[
      {
         "first_name":"John",
         "last_name":"Smith",
         "group":"3",
         "email":"[email protected]"
      },
      {
         "first_name":"John",
         "last_name":"Doe",
         "group":"3",
         "email":"[email protected]"
      }
   ],
   "meta":{
      "pagination":{
         "total":2,
         "count":2,
         "per_page":500,
         "current_page":1,
         "total_pages":1,
         "links":[

         ]
      }
   }
}

I'm trying to use Guzzle to import into my Laravel app

$client = new \GuzzleHttp\Client();
      $response = $client->request('GET', 'http://localhost/members.json');
      $data = (string) $response->getBody();

and then a foreach to loop over each record and then add it to the database. Right now though I'm struggling to drill down into a record.

What am I missing?

EDIT: Here's the foreach

foreach ($data['data'] as $person) {
        Contact::create(array(
          'name' => $person->first_name,
        ));
      }

Upvotes: 2

Views: 4128

Answers (1)

Vasil Rashkov
Vasil Rashkov

Reputation: 1834

Your $data variable holds json. Lets first make it a nice array and then loop it through

$response = json_decode($data, true);

Now the loop itself:

foreach($response['data'] as $element) {
    $firstName = $element['first_name'];
    $lastName = $element['last_name'];
    $group = $element['group'];
    $email = $element['email'];
    //Now here you can send it to the modele and create your db row.
}

Upvotes: 7

Related Questions