Laravel, Call to undefined function Database\Seeders\factory()

Jakub Padło picture Jakub Padło · Sep 9, 2020 · Viewed 14.4k times · Source

I get the title error when I run command:

php artisan db:seed

My screenshot: enter image description here

I have no idea where this problem comes from. I was searching for code examples and solution but I haven't found anything :(

ArticlesTableSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
// use Laracasts\TestDummy\Factory as TestDummy;

class ArticlesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Models\Article::class, 30)->create();
    }
}

ArticleFactory.php

<?php

namespace Database\Factories;

use App\Models\Model;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class ModelFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = App\Models\Article::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'title' => $faker->text(50),
            'body' => $faker->text(200)
        ];
    }
}

DatabaseSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call(ArticlesTableSeeder::class);
    }
}

Thank you in advance for your help!

Answer

Krzysiek_Sadowski picture Krzysiek_Sadowski · Sep 15, 2020

In laravel 8 the default route namespace was removed.

Try to change:

ArticlesTableSeeder.php:

 factory(App\Models\Article::class, 30)->create();

to:

\App\Models\Article::factory()->count(30)->create(); 

ArticleFactory.php:

protected $model = App\Models\Article::class;

to:

protected $model = \App\Models\Article::class;

and you will probably have to change:

 'title' => $faker->text(50),
            'body' => $faker->text(200)

to:

 'title' => $this->faker->text(50),
        'body' => $this->faker->text(200)