Search code examples
phplaravellaravel-migrationslaravel-seeding

Saving seeding data to database in Laravel


I am participating in a Laravel course. The course was supposed to be laravel 8, but it is 30/70 laravel 8, and laravel 5 was outdated and is slowly updated. The problem is saving seeding data to a database (MySQL). I can save Users to the database in the code but cannot save Blogposts Or comments. The blog posts are supposed to be saved with random user IDs from all user tables so that the specific user who made the post would be able to edit the post he made, not the others. Also, comments have the same story, but comments are randomly assigned to posts. Previously it has been tried to save posts to a database using PHP artisan tinker.

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        $users = User::factory()->count(20)->create();
        dd($users->count());
        $posts = BlogPost::factory()->count(50)->make()
            ->each(function ($post) use ($users) {
            $post->user()->associate($users->random())->save();
        });
        $comments = Comment::factory()->count(150)->make()
            ->each(function ($comment) use ($posts) {
            $comment->blog_post_id = $posts->random()->id;
        });
    }
}

When making a migration, there are no errors shown. For migration, we use the following.

php artisan migrate:refresh --seed

Solution

  • Well, the meaning of dd() is dump and die. Therefore you are stoping the seed execution after the User factory.

    Just remove the dd() and seed should be executed as expected

    <?php
    namespace Database\Seeders;
    use App\Models\User;
    use App\Models\BlogPost;
    use App\Models\Comment;
    use Illuminate\Database\Seeder;
    class DatabaseSeeder extends Seeder
    {
        public function run()
        {
            $users = User::factory()->count(20)->create();
            // dd($users->count()); <-- This stops the seed execution
            $posts = BlogPost::factory()->count(50)->make()->each(function($post) use ($users) {
                $post->user()->associate($users->random())->save();
            });
            $comments = Comment::factory()->count(150)->make()->each(function ($comment) use ($posts){
                $comment->blog_post_id = $posts->random()->id;
            });
        }
    }