Answer the question
In order to leave comments, you need to log in
Are there any methods in Laravel to dynamically add fields to a MySQL-based model/entity?
There is a need to add and remove model/entity fields from the admin panel (for example: so that the site administrator can add a field to the user profile and organize filtering on them).
Does Laravel have any out-of-the-box mechanisms for doing this in the MySQL context, without using json type fields?
Roughly speaking: to add a field to the table, a new property to the model class, and so on.
Answer the question
In order to leave comments, you need to log in
You created a problem where there is none because you combined two unrelated problems.
Adding and other changes can be seen in migrations, there is a ready component \Illuminate\Database\Schema\Builder
After that, the field is no different from the rest. This is not Doctrine, where fields must be explicitly written.
The second task is the work of the admin panel, it has nothing to do with the way the field appears in the model. The same elementary dynamic sorting or filtering is done head-on.
Let's say
?filterBy=fieldName&filterValue=value&filteOperation=%3D comes in the url
in the controller
$model->where($request->get('filterBy'), urldecode($request->get('filterOperation')), $request-> get('filterValue'));
And it doesn't matter how you added the column and whether it exists at all in the database, Eloquent does not check for this.
But don't forget about safety.
change the database - please DB::statement( .... );
, but all the magic of laravel will of course be unavailable,
this is how I made the engine for the store with custom fields
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question