ahoi
113
2
Laravel

Dynamic custom fields: JSON, Pivot, morphToMany?

Posted 1 month ago by ahoi

Hello everybody,

I'm currently working on a "custom fields" feature for my Laravel-app.

What it's supposed to do

Each CustomField should be editable by the user. The CustomField can have a type (string, int, ...) and a value.

Now the created CustomFields can be added to another model (Maybe: User).

Expected result

The values of the custom fields should be callable using something like $user->fields->company->value

It should be easy to iterate through the fields like this: $user->fields()->each(...)

My problem

I'm not sure which way to go: Of course I could just create a model called CustomField and a table with

  • id
  • type

and save them to the User as JSON ($user->fields would be type JSON). But I am not sure, whether this is the best way to go, because I also would like to make the fields searchable later. So maybe pivot is the way to go? Or even morphToMany?

Which way is the most "Laravel-style" way to go?

Thank you for your thoughts (and maybe 1-2 examples ;-) )

Please sign in or create an account to participate in this conversation.