Search code examples
phpmysqllaravelmigrationlaravel-5.3

Create table with few rows with migration in laravel


I would like to create a table that will save the data for only 10 rows. How can I do it via migration in Laravel 5.3?


Solution

  • Laravel 5.3 provides seeding, also combined with model factories. I'm guessing you're using Eloquent models instead of query builder.

    Model Factory

    Here an example from Laravel (https://laravel.com/docs/5.3/seeding#using-model-factories)

    factory(App\User::class, 10)->create();
    

    This code creates 10 fake users via the User Eloquent model. The declaration of a fake user could be done in database/factories/ModelFactory.php.

    Seeding

    Again, a partial example from Laravel (https://laravel.com/docs/5.3/seeding#writing-seeders). You can call the model factory directly from the existing DatabaseSeeder (no need to create a new seeder).

    <?php
    
    use Illuminate\Database\Seeder;
    use Illuminate\Database\Eloquent\Model;
    
    class DatabaseSeeder extends Seeder
    {
        /**
         * Run the database seeds.
         *
         * @return void
        */
        public function run()
        {
            factory(App\User::class, 10)->create();    
        }
    }
    

    Run

    • php artisan db:seed to seed the data in existing table structure
    • php artisan migrate:refresh --seed for completely rebuilding your database and running the seeders

    Full documentation and examples, see the provided links above.