Home > OS >  What causes the 'Unknown format "factory"' error in this Laravel 8 app?
What causes the 'Unknown format "factory"' error in this Laravel 8 app?

Time:03-08

I am working on a Laravel 8 app with users and posts.

The objective is to create a bunch of posts (I already have users).

namespace Database\Factories;
// import Post model
use App\Models\Post;
// import User model
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

class PostFactory extends Factory {
  /**
   * The name of the factory's corresponding model.
   *
   * @var string
   */
   protected $model = Post::class;
 
  /**
   * Define the model's default state.
   *
   * @return array
   */
   public function definition() {
    return [
            'title' => $this->faker->sentence(3),
            'description' => $this->faker->text,
            'content' => $this->faker->paragraph,
            'user_id' => $this->faker->factory(App\Models\User::class),
        ];
    }
}

The problem

I run php artisan tinker then Post::factory()->count(100)->create() in the terminal and I get:

InvalidArgumentException with message 'Unknown format "factory"'

UPDATE

I replace my return statement with:

 return [
    'title' => $this->faker->sentence(3),
    'description' => $this->faker->text,
    'content' => $this->faker->paragraph,
    'user_id' => User::factory(),
];

I get this in the terminal:

Class 'Database\Factories\UserFactory' not found

Questions:

  1. Where is my mistake?
  2. Does the fact that I get the error Class 'Database\Factories\UserFactory' not found mean that I need to create a UserFactory factory? Because there isn't one. (I wanted to create posts, not users).

CodePudding user response:

I don't suppose there is $this->faker->factory(..).

You can do

'user_id' => App\Models\User::factory()->create()->id,

EDIT: 'user_id' => App\Models\User::factory(),

CodePudding user response:

Creating a UserFactory factory and using the below return statement did the trick:

return [
    'title' => $this->faker->sentence(3),
    'description' => $this->faker->text,
    'content' => $this->faker->paragraph,
    'user_id' => User::factory(),
];

So, the PostFactory class looks like this:

class PostFactory extends Factory {
  /**
   * The name of the factory's corresponding model.
   *
   * @var string
   */
   protected $model = Post::class;
 
  /**
   * Define the model's default state.
   *
   * @return array
   */
   public function definition() {
        return [
                'title' => $this->faker->sentence(3),
                'description' => $this->faker->text,
                'content' => $this->faker->paragraph,
                'user_id' => User::factory(),
        ];
    }
}
  • Related