I get the title error when I run command:
php artisan db:seed
My screenshot:
I have no idea where this problem comes from. I was sear
If you are using version 8 of laravel, look at the upgrade guide. "Laravel's model factories feature has been totally rewritten to support classes and is not compatible with Laravel 7.x style factories. However, to ease the upgrade process, a new laravel/legacy-factories package has been created to continue using your existing factories with Laravel 8.x. You may install this package via Composer:
composer require laravel/legacy-factories"
https://laravel.com/docs/8.x/upgrade#seeder-factory-namespaces
ArticlesTableSeeder.php
<?php
namespace Database\Seeders;
use App\Models\Article;
use Illuminate\Database\Seeder;
class ArticlesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Article::factory()->times(30)->create();
}
}
ArticleFactory.php
<?php
namespace Database\Factories;
use App\Models\Article;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class ArticleFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Article::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'title' => $this->faker->text(50),
'body' => $this->faker->text(200)
];
}
}
All suggestions that were mentioned here are correct.
However, you must run composer require laravel/legacy-factories
in order for the code to run if you're using Laravel 8.
In case you get an error that says Class 'Database\Factories\ArticleFactory' not found
then make sure you have class ArticleFactory extends Factory
and not ModalFactory.
And make sure you're using HasFactory in the Article Model like here.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use HasFactory;
}
Try to change
factory(App\Models\Article::class, 30)->create();
to
App\Models\Article::factory()->count(30)->create();
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)