2

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,
        ));
      }
3
  • 1
    The $data variable holds that json you showed us ? Commented Aug 13, 2016 at 14:41
  • yeah, but I'm struggling to loop over it and pass the values from it to the model. Commented Aug 13, 2016 at 15:24
  • Have you ran it through json_decode and then tried doing something like foreach ($data['data'] as $item)? Commented Aug 13, 2016 at 15:36

1 Answer 1

7

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.
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Vasil - that's exactly what I was missing :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.