Assume we have a posts table and there is a field like user_id. So when we need to seed our data into the posts table, then we need user_id in the post factory class. So in this tutorial, I will show you, laravel faker with relationship example. So you will learn laravel factory create with relationship.

So let's see the posts table like this:

<?php

use App\Models\User;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->foreignIdFor(User::class)
                ->constrained()
                ->cascadeOnUpdate()
                ->cascadeOnDelete();
            $table->mediumText('title')->unique();
            $table->boolean('is_published')->default(true);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
};

 

Now create a factory class for the post by using the below command:

php artisan make:factory PostFactory

 

Now update it like this:

Database\Factories\PostFactory.php

<?php

namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Post>
 */
class PostFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition()
    {
        return [
            'user_id' => User::factory(),
            'title' => fake()->paragraph()
        ];
    }
}

 

Now register it inside the seeder class like this:

Database\Seeders\DatabaseSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {  
       \App\Models\User::factory(10)->create();
       \App\Models\Post::factory(50)->create();
    }
}

 

Now if you run the below command:

php artisan db:seed

 

Then it will save dummy data into your users and posts table:

laravel-9-faker-with-relationship

Read also: How To Define IP And MAC Address Column Type In Laravel

 

Conclusion

I have tried to discuss the clear concept of laravel faker with relationship. Now we know ilaravel factory create with relationship. Hope this laravel 9 factory create with relationship tutorial will help you.