Skip to content
Advertisement

Laravel eloquent multiple belongsTo seeding

I have three models, User, Category and Article.

Article belongs to both a User and a Category where the foreign keys user_id and category_id are not null.

Am lost trying to seed the database with fake data via factories accordingly, here’s the seeding code…

JavaScript

I’ll get one of two errors, either

Column user_id doesn’t have a default value

Or

Column category_id doesn’t have a default value

Which is logical due to the Article table migration

JavaScript

How can I pass the category_id or user_id to the factory call?
Is there a better way to acheive this?

Thanks in advance

Advertisement

Answer

You can override attributes for your factory by passing an array with the desired attributes to the make() method:

Change

JavaScript

to

JavaScript

to override the category_id attribute.

https://laravel.com/docs/6.x/database-testing#using-factories

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement