Home > database >  Error when using tinker to generate Users and Posts (Laravel)
Error when using tinker to generate Users and Posts (Laravel)

Time:02-04

I have the following BlogPostFactory

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;


class BlogPostFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'title' => $this->faker->sentence,
            'body' => $this->faker->paragraph(30),
            'user_id' => User::factory(),
        ];
    }
}

I've been trying to use tinker to generate posts and users,

 \App\Models\BlogPost::factory()->count(10)->create();

but I'm getting the following error:

PHP Error:  Class "Database\Factories\User" not found in C:\Program Files\Ampps\www\example\database\factories\BlogPostFactory.php on line 19

Does anyone know how to fix this? Thanks for you help!

CodePudding user response:

You're missing the namespace on the User class.
By default PHP takes the current namespace namespace Database\Factories;, hence the error.

Instead of: (Unqualified name)

// ...
'user_id' => User::factory(),
// ....

Use this: (Fully qualified name)

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

Addendum

Don't forget to restart your current tinker session. (Close the current one (exit;) and open a new tinker session (php artisan tinker)).

  •  Tags:  
  • Related