Home > front end >  Laravel 8.83: Dynamic columns in table
Laravel 8.83: Dynamic columns in table

Time:08-22

In the application, we have 2 modules called "Type" and "Lists".

When the user created in type, it will be display in the creating of lists.

For example

There's 2 data in type: Price & Unit of Measurement

Now upon creating in lists those added in types will be display as select.

Below picture is the expected output:

enter image description here

I tried what I've searched in the internet but it didn't work. It says

enter image description here

For reference: https://laracasts.com/discuss/channels/laravel/create-columns-in-a-table-dynamically

CONTROLLER

$items      = ['another_test1','another_test'];
foreach ($items as $i => $item) {
    # code...
    // if($i == 1){
        if (Schema::hasColumn('approvals', $item)) {
            Schema::table('users', function (Blueprint $table) use ($item){
               $table->dropColumn($item);
            });
        }else{
            Schema::table('approvals', function (Blueprint $table) use ($item) {
                $table->longText($item);
            });
        }
    // }
}

Question: How do I make a dynamic columns in a table?

CodePudding user response:

I think it's better to use another table that stores your dynamic fields and it has 2 columns

For example table name custom_fields

the columns are :

field_name

field_value

Whenever a new field comes up you insert it with its value

CustomField::create(['field_name' => 'type','field_value' => 'price');

Wordpress uses that logic too

CodePudding user response:

I figured it out. I just removed the Blueprint and it worked

$items      = ['another_test1','another_test'];
foreach ($items as $i => $item) {
    # code...
    // if($i == 1){
        if (Schema::hasColumn('approvals', $item)) {
            Schema::table('users', function ($table) use ($item){
               $table->dropColumn($item);
            });
        }else{
            Schema::table('approvals', function ($table) use ($item) {
                $table->longText($item);
            });
        }
    // }
}
  • Related