Home > other >  Initialize table in Eloquent ORM with default values
Initialize table in Eloquent ORM with default values

Time:01-04

I'm creating a API in Lumen framework, using Eloquent ORM to acess my databases. I've already used Factories and Models to generate random rows in my table.

What I want know is to generate real data, default values if my table is empty. I'll have a units table, to store possible unit values (Kilograms, piece, liters etc). I've created a migration class to create the table, but I'd like to create this table with some default rows , so it's not created empty. They will not be random, they will be the real values the user will access, even in production. They can be changed afterwards, but I'd like the system to initialize with these values.

CodePudding user response:

You have two options:

  1. Create a seeder that fills in the database with the values.

  2. Add the values directly into the migration. For that, you just need to create an associated array, and use DB::table('table')->insert(). Put that into the migration in the up() function, after the create() call. I find this helpful for small sets of values. It would look like this:

DB::table('units')->insert([
    ['type' => 'liter'],
    ['type' => 'quart'], 
    ['type' => 'gallon'],
    ['type' => 'kilogram']
]);  
  •  Tags:  
  • Related