Search code examples
phplaravellaravel-5php-7laravel-seeding

How write seeder in Laravel


I have table taggable, it's table for Many To Many Polymorphic Relations (Tag and post):

taggable_id - id of Post
tag_id - id of Tag
taggable type - location of post model (default value"App/Models/Posts/Post")
is_search_term - boolen (0 or 1)

How create a seeder which each time create same records for relations?


Solution

  • Tag_id will be created by db automatically if it is set to primary key, taggable_id you get values from Tag model.

    You can try something like this;

    $factory->define(App\Tag::class, function (Faker\Generator $faker) {
        return [
            'taggable_id' => random_int(\DB::table('posts')->min('id'), \DB::table('posts')->max('id')),
            'is_search_term'=>$faker->numberBetween(0,1),
    'taggable_type'=>$faker->sentence(2),
    
        ];
    });