Shibbir
Shibbir

Reputation: 2031

Laravel 8 - Class 'Database/Factories/User' not found

I have this PostFactory.php file in database->factories directory:

<?php

namespace Database\Factories;

use App\Models\Post;
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 [
            'user_id'   => User::factory(),
            'title' => $this->faker->sentence,
            'message' => $this->faker->paragraph
        ];
    }
}

Now, when I run this command

Post::factory()->create();

from the tinker

I got that error message

Class 'Database/Factories/User' not found

:( Is there anything I am missing?

enter image description here

Upvotes: 4

Views: 12188

Answers (4)

Sharunas Bielskis
Sharunas Bielskis

Reputation: 1203

Quit and then start again artisan tinker. This worked for me.

Upvotes: 0

riom
riom

Reputation: 91

FYI just run:

composer dump-autoload

It can be that the class is not autoloaded.

Upvotes: 4

Faizan
Faizan

Reputation: 59

As i Also had same Issue .First i changed my factory name same as name of model . Like if we have Blog Model .. We will make BlogFactory . so it can find the name of factory .

Upvotes: 0

melvin atieno
melvin atieno

Reputation: 1033

You need to import the User Model. For Laravel 8, Your PostFactory.php file should look like so;

<?php

namespace Database\Factories;

use App\Models\User;
use App\Models\Post;
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 [
            'user_id'   => User::factory(),
            'title' => $this->faker->sentence,
            'message' => $this->faker->paragraph
        ];
    }
}

check laravel docs on writing factories for more info.

UPDATE:

As for the error here on prnt (picked it up in the comments), You will need to provide more information.

However to start you up consider checking your database for:

  • A post that does not have a user_id. I.e one that you might have added before adding the foreign key constraint and therefore does not belong to any user.

If that's the case consider removing it or use tinker to manually assign a foreign key(i.e associate the post with a user) then try and create factories again. As you are trying to enforce a required column to existing data that does not already have it.

Upvotes: 18

Related Questions