I'm making a form builder tool in Laravel. I have a form model and several form field models (for instance an input model, a textarea model, a select model and so on). I'm trying to load all form fields that belong to a specific form with a function like $form->fields() and then loop over them and generate the appropriate output for each field.
I think a polymorphic relationship with an intermediate table is the way to go here, but I'm having trouble finding the correct functions to use. Any help would be greatly appreciated.
Below are the skeletons of the models I have:
class Form extends Model
{
// Returns all fields belonging to this form.
public function fields() {
}
}
class Input extends Model
{
// Returns the form to which this input field belongs.
pulic function form() {
}
}
class Textarea extends Model
{
// Returns the form to which this textarea field belongs.
pulic function form() {
}
}
And these are examples of the corresponding database structure:
form
- id
input
- id
textarea
- id
forms_fields
- id
- form_id
- field_id
- field_type
The questions I have:
- Is this the best setup to achieve what I want?
- Which functions to use?
I tried functions like morphTo and morphToMany but I don't seem to get it right. When I read the documentation it seems that my use case is different from the ones described there.
I expected my $form->fields() function to return a collection with field type models but mostly get an sql error: select * from "forms" where "forms"."" is null
. I must be doing something wrong but I don't know what.