1

So I am trying to seed data into my dB from an external api and not the default faker using the model factory in Laravel and I am stuck. Below is my code:

$factory->define(\App\Models\State::class, function(){
    $client = new Client();
    $stateQuery = $client->get('http://states-and-cities.com/api/v1/states');
    $states = $stateQuery->getBody();
    $states = json_decode($states, true);
    foreach ($states as $state) {
        return [
            'name' => $state['name'],
        ];
    }
});

So what's happening is that the return as expected is seeding only one record but I need it it to seed the whole records. How can I fix this?

Fatimah
  • 722
  • 7
  • 16
  • You can insert your data through sql insert.running a for loop of array and insert each record.@FatimahSanni – Parth Mahida Nov 10 '16 at 14:00
  • 1
    It's obvious because you finish the whole method (function, block of code) on the first iteration with `return`. Remove `return` and collect the results in a buffer array. – Alexey Shokov Nov 11 '16 at 09:37

1 Answers1

0

You can try as:

$client = new Client();
$stateQuery = $client->get('http://states-and-cities.com/api/v1/states');
$states = $stateQuery->getBody();
$states = json_decode($states, true);
foreach ($states as $state) {
    \App\Models\State::create(['name' => $state['name']]);
}
Amit Gupta
  • 17,072
  • 4
  • 41
  • 53
  • Yeah, that would work if it was just the seeder file but I want to use the model factory so the code is a little different. – Fatimah Nov 10 '16 at 13:58