@iamfaiz hey.
I believe there isn't any method which will parse that input and figure out on its own how to persist this data. However, you can pretty easily create one.
If you want and it feels better for you, we can try to use the available functionality and when we execute Test::create($data); we will automatically let it know how to parse its relationships. Please note that what I'm going to try here isn't tested and I haven't tested it but the idea seems to be right.
To make it work we need to add to the fillable fields on Test.php the questions value - yes, I know there is no such a column in the database. We will specify this so we can then just pass the whole data and make the Test class know how to save its relationship.
Now let's add a method to the Test class:
public function setQuestionsAttribute($questions)
{
foreach ($questions as $question) {
$this->questions()->create($question);
}
}
Now go to Question.php and add options to the fillable fields.
We will now add a method to Question.php
public function setOptionsAttribute($options)
{
foreach ($options as $option) {
$this->options()->create($option);
}
}
That should do the trick. Note that this way is assuming that the input fields name are the same as your DB column names.
By the way, if it doesn't work, you can just create a method on the Test class which will just have a nested foreach loop and save each relationship manually. Should be fairly easy to do that. It may take the shape of:
public static function publish($data)
{
$test = new static($data);
foreach ($data['questions'] as $obj) {
$question = $test->questions->create($obj);
foreach ($obj['options'] as $option) {
$question->options()->create($option);
}
}
}
We can refactor it to be a recursive function and use the Grammar helper to figure out the relationship names based on the keys that holds an array but let's try to get it work first before refactoring.
Hope that it helps you!