I have a database table look like this
|id |col2|col3|col4|
-------------------
| 1 |elm0|....|....|
| 2 |elm1|....|....|
| 3 |elm2|....|....|
|...|....|....|....|
|N+1|elmN|....|....|
I want to fill the col2
with data from array (not in random way). Example array:
$dataArray = array(elm0, elm1, elm2,...)
I created this factory:
<?php
use Faker\Generator as Faker;
$factory->define(App\Unit::class, function (Faker $faker) {
$dataArray = array(elm0, elm1, elm2,...,elmN);
return [
'col2' => $dataArray[$index];
'col3' => $faker->'whatever';
'col4' => $faker->'whatever';
];
});
How I can do this?
<?php
use Faker\Generator as Faker;
$factory->define(App\Unit::class, function(Faker $faker) {
// Grab a random unit
$unit = App\Unit::orderByRaw('RAND()')->first();
// Or create a new unit
$unit = factory(App\Unit::class)->create();
return [
'id' => $unit->id,
'col2' => $faker->'whatever',
'col3' => $faker->'whatever',
'col4' => $faker->'whatever',
];
});
Please check if it is work for you.
you can build like that:
<?php
use Faker\Generator as Faker;
$factory->define(App\Unit::class, function(Faker $faker) {
$data = array(elm0, elm1, elm2,...,elmN);
foreach($data as $kye=>$value) {
$result['id'] = $key;
$result['col2'] = $value;
$result['col3'] = $faker->'whatever';
$result['col4'] = $faker->'whatever';
}
return $result;
});
When you need to run an array, often foreach()
solve your problem.
Hope that help you.
Cheers.
Had a similar problem and decided to skip the factory part and use only seeder. I got to the solution while reading this: Seed multiple rows at once laravel 5 answer by lukasgeiter.
First you make a seeder with:php artisan make:seeder UnitsTableSeeder
Then you will have in your seeder something like this:
<?php
use Faker\Generator as Faker;
use Illuminate\Database\Seeder;
class UnitsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$faker = new Faker;
$data = ['elm0', 'elm1', 'elm2',...,'elmN'];
$rows = [];
foreach ($data as $element) {
$rows[] = ['col2' => $element, 'col3' => $faker->'whatever', 'col4' => $faker->'whatever'];
}
App\Unit::insert($rows);
}
}
After this you can seed your Units table like a sir :)
php artisan db:seed --class=UnitsTableSeeder