Assume we have a table of users
, and posts
. The relationship between them is a user has many posts. Now we want to seed data with those tables together. How we can do that?
So if you do not know laravel 9 seed one to many relationships, then this laravel factory relationship one to many tutorials are going to be for you. In this tutorial, I will show you laravel factory seed relationship one to many.
Now run the below command to create these two factory like:
php artisan make:factory UserFactory
php artisan make:factory PostFactory
Now I am assuming you have a Post
model which contains user_id and title
. Now update the Post model like:
App\Models\Post.php
<?php
namespace App\Models;
use Illuminate\Support\Facades\URL;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
class Post extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'title',
];
}
Read also: Laravel 9 Factory Create With Relationship Example
Laravel by default provides UserFactory like:
Database\Factories\UserFactory.php
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
*/
class UserFactory extends Factory
{
public function definition()
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi',
'remember_token' => Str::random(10),
];
}
public function unverified()
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}
So now open DatabaseSeeder
class and update it like:
Database\Seeders\DatabaseSeeder.php
<?php
namespace Database\Seeders;
use App\Models\Post;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
class DatabaseSeeder extends Seeder
{
public function run()
{
User::factory(20)->create()
->each(function($user) {
Post::create([
'user_id' => $user->id,
'title' => fake()->paragraph()
]);
});
}
}
Now if you run the below command:
php artisan db:seed
Then it will save dummy data into your users and posts table:
Conclusion
I have tried to discuss the clear concept of laravel factory one to many. Now we know laravel 9 factory one to many. Hope this laravel factory relationship one to many tutorial will help you.