Factory for extended Model in laravel 8

Viewed 355

I'm facing an issue on laravel 8, I created :

  • A class called CRUDModel that extends Illuminate\Database\Eloquent\Model
  • A Model called Stuff that extends CRUDModel
  • A factory called StuffFactory

When I call Stuff::factory()->count(60)->create(); I get this error :

SQLSTATE[HY000]: General error: 1364 Field 'title' doesn't have a default value (SQL: insert into `stuffs` (`updated_at`, `created_at`) values (2020-10-12 15:28:06, 2020-10-12 15:28:06))

I guess it's because of Stuff doesn't extend directly Model but I'm not sure. Here's my class :

<?php
namespace App\Crudite\Model;

use Illuminate\Database\Eloquent\Model;
use App\Crudite\Model\CRUDIntel;

class CRUDModel extends Model
{
    use CRUDIntel;

    ...
    
}

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Crudite\Model\CRUDModel;

class Stuff extends CRUDModel
{
    use HasFactory;
    ...
}
<?php

namespace Database\Factories;

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

class StuffFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Stuff::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            "title" => $this->faker->name,
            "content" => $this->faker->paragraph,
            "thumbnail" => "https://placekitten.com/1200/300"
        ];
    }
}

1 Answers

For others who may have the same problem, what @Kermito does for making a factory out of an extended model is actually correct. Simply make a factory out of the extended model, as you would a regular model and it should work. In this case, however, it is the faker functions for title and content that have an error, which could be why they are not being added into the insert statement as shown in the error. Faker has updated their syntax and the lines of code should be:

//note the parantheses ()
 "title" => $this->faker->name(),
 "content" => $this->faker->paragraph(),
Related