Home > other >  How To Seed a Laravel Factory with Specific Custom Data
How To Seed a Laravel Factory with Specific Custom Data

Time:10-01

I have a collection of places with GPS coordinates that I want to use to seed a table of "places". The data includes a custom identifier, district, address, and lat/long coordinates. This is important for testing purposes. So instead of insert a bunch of fake data, I want to insert a set of predefined data that makes sense. How do I do this in the Laravel Seeder and Factory?

1851    Long Ridge    3196 High Ridge Rd    41.17530211     -73.56473089000001                      
1852    Long Ridge    Fairway Dr            41.17431056     -73.56484688            
1850    Long Ridge    3143 High Ridge Rd    41.17365836     -73.56433814                    
1853    Long Ridge    69 Fairway Dr         41.17321183     -73.56777862
1854    Long Ridge    137 Fairway Dr        41.17195677     -73.56931346
1849    Long Ridge    3081 High Ridge Rd    41.17156046     -73.56332694                    
1857    Long Ridge    55 Greens Cir         41.17155058     -73.56715740999999      
1856    Long Ridge    10 Greens Cir         41.17111036     -73.56860723

CodePudding user response:

If you have predefined data in JSON format then you can check the below seeder code.

database/seeders/LocationSeeder.php

<?php
  
namespace Database\Seeders;
  
use Illuminate\Database\Seeder;
use App\Models\Location;
use File;
  
class LocationSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Location::truncate();
  
        $json = File::get("database/data/location.json");
        $locations = json_decode($json);
  
        foreach ($locations as $key => $value) {
            Location::create([
                "name" => $value->name,
                "id" => $value->id,
                ........
            ]);
        }
    }
}

if it is in excel format then you can use the below package for the same.

https://github.com/Flynsarmy/laravel-csv-seeder

and it is an array then you can directly insert it using the foreach.

Please let me know if you have data in any other format.

  • Related