I am creating tables in PHPMyAdmin using Laravel Migrations. One of the things that I want to do is have a Question Table and Answers Table where 1 question can have 4 answers (Multiple choice). I want to link the answers and the question with a relationship.
Is it possible to set a primary/foreign key in Laravel in such a way that each time a new Question row is created, the question is connected two 4 answers (when created)?
The rows will be populated manually but they need to be linked.
Is this possible and if so I would appreciate any solutions.
Thank you in advance.
2
Answers
Yes, it’s possible, and here is how
in the file migration of answers, you may add
unsignedBigInteger(question_id)
.in the model
Question
you may addin the creation of the answer, you may pass in the request
question_id
that is related to this answerIs that what are you asking for or I misunderstood?
Yes, a common way to do it is to subscribe to the
created
event for theQuestion
Model. There are several ways to do this, but I usually either register the listeners onbooted()
in the Model itself or use Observers if I have a lot of event subscriptions going on and want it a little more structured.You can register a
created
listener in a Model like this:In this example, I assumed a
sort
column in your schema just for demonstration purposes. If you don’t want to prefill any columns on the newAnswer
instances, you can of course just pass in empty arrays ([]
) instead.You can read more about this in the docs: https://laravel.com/docs/8.x/eloquent#events