Post table seeder laravel 10

Created at 30-Jan-2024 , By samar

Building your Laravel application can be an exciting journey, but starting with an empty database isn't always ideal. This is where seeding comes in, allowing you to inject pre-defined data and see your application come to life. Today, we'll focus on seeding the Post table, using both factories and the seeder class. Get ready to unleash a vibrant world of dummy data!

Step 1: Crafting the Post Factory:

  1. Open your terminal: Navigate to your Laravel project directory using the cd command.

  2. Generate the Factory: Run php artisan make:factory PostFactory. This creates a file named PostFactory.php within the database/factories directory.

  3. Define the Dummy Data: Open the PostFactory.php file and edit the definition method. Here, you can specify the fields you want to populate with dummy data. Let's add some essentials like title, body, user_id, is_published, created_at and updated_at:

Here is the PostFactory.php code :

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Model>
 */
class PostFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'title' => $this->faker->sentence,
            'body' => $this->faker->paragraph(20, 40),
            'is_published' => $this->faker->randomElement(['0', '1']),
            'created_at' => now(),
            'updated_at' => now(),
            'user_id' => \App\Models\User::all()->random()->id
        ];
    }
}

Step 2: Building the Post Seeder:

  1. Generate the Seeder: Run php artisan make:seeder PostTableSeeder. This creates a file named PostTableSeeder.php within the database/seeders directory.

  2. Populate the Database: Open the PostTableSeeder.php file and add the following code:

public function run(): void
{
    \App\Models\Post::factory()->count(5)->create();
}

Step 3: Seeding in Action:

  1. Now open database\seeders\DatabaseSeeder.php and place below code in it.
public function run(): void
{
    // \App\Models\User::factory(10)->create();
    $this->call([
        UserTableSeeder::class,
        PostTableSeeder::class
    ]);
}
  1. Run the Seeder: In your terminal, execute php artisan db:seed. This triggers the PostTableSeeder and injects your dummy data into the database.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.