'Morph field doesn't have a default value when seeding factory relationship
I have a Recipe
and Review
model:
class Recipe extends Model
{
use HasFactory;
protected $guarded = ['id'];
public function reviews(): MorphToMany
{
return $this->morphToMany(Review::class, 'reviewable');
}
}
class Review extends Model
{
use HasFactory;
protected $guarded = ['id'];
}
Each has a factory:
class RecipeFactory extends Factory
{
protected $model = Recipe::class;
public function definition()
{
return [
'name' => $this->faker->sentence(5, true),
];
}
}
class ReviewFactory extends Factory
{
protected $model = Review::class;
public function definition()
{
return [
'review' => $this->faker->paragraphs(1, true),
];
}
}
When I try to seed new test records using this:
Recipe::factory()->hasAttached(
Review::factory()
->count(5)
);
I get the SQL error:
SQLSTATE[HY000]: General error: 1364 Field 'reviewable_type' doesn't have a default value
How do I get Laravel to fill in the correct morph reviewable_type
and reviewable_id
values when seeding the related records?
Solution 1:[1]
In my case, I have a program, and a form, the form can be attached to various tables.
When I created my seeder I would grab a program, create a form, and then got the error General error: 1364 Field 'formable_type' doesn't have a default value
I fixed this by updating my migration to use nullableMorphs
.
$table->nullableMorphs('formable');
Hope that will help someone.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Adam Patterson |