I have three tables; users, categories, posts and have a relationship between them as
- A user can have many posts
- A post belongs to user and can have many categories
- A category can have many posts
PostFactory.php
public function definition()
{
return [
'user_id' => User::factory(),
'category_id' => Category::factory(),
'title' => $this->faker->sentence,
'slug' => $this->faker->slug,
'excerpt' => $this->faker->sentence,
'body' => $this->faker->paragraph
];
}
UserFactory.php
public function definition()
{
return [
'username' => $this->faker->unique()->userName,
'name' => $this->faker->name(),
'email' => $this->faker->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => 'yIXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
}
CategoryFactory.php
public function definition()
{
return [
'name' => $this->faker->word,
'slug' => $this->faker->slug
];
}
So, Whenever I am creating a fake data for post, using Tinker as Post::factory()->create() then it basically create and persist new user, new category and new post to the database but when I am using Post::factory()->make() then it should return the instance of post and make the instance of user and category return it to user_id and category_id but not persist the User and Category entry to database until I call save or create method on post. But it's creating and saving the new User and new Category to the database and returning a instance to Post. So why does it persist User and Category to database.
** AND **
Also, If I use the create method for category inside postfactory as 'category_id' => Category::factory()->create(), then it should save the category to database and return an instance when I will be using Post::factory()->create inside tinker but why it's not good practice to do that('category_id' => Category::factory()->create()) or what's the difference apart from this one "saving to database and returning an instance when using create method, and If I don't then it will first return an instance but will save later"
PostFactory.php
public function definition()
{
return [
'user_id' => User::factory(),
'category_id' => Category::factory()->create(),
'title' => $this->faker->sentence,
'slug' => $this->faker->slug,
'excerpt' => $this->faker->sentence,
'body' => $this->faker->paragraph
];
}