How to create dynamic table with dynamic fields in Laravel?

Posted by LaravelIndia - 1 year ago
php artisan make:controller TableController

/app/Http/Controllers/TableController.php:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;

Create dynamic table along with dynamic fields

public function createTable($table_name, $fields = [])
{
    // laravel check if table is not already exists
    if (!Schema::hasTable($table_name)) {
        Schema::create($table_name, function (Blueprint $table) use ($fields, $table_name) {
            $table->increments('id');
            if (count($fields) > 0) {
                foreach ($fields as $field) {
                    $table->{$field['type']}($field['name']);
                }
            }
            $table->timestamps();
        });

        return response()->json(['message' => 'Given table has been successfully created!'], 200);
    }

    return response()->json(['message' => 'Given table is already existis.'], 400);
}



public function operate()
{
    // set dynamic table name according to your requirements

    $table_name = 'products';

    // set your dynamic fields (you can fetch this data from database this is just an example)
    $fields = [
        ['name' => 'field_1', 'type' => 'string'],
        ['name' => 'field_2', 'type' => 'text'],
        ['name' => 'field_3', 'type' => 'integer'],
        ['name' => 'field_4', 'type' => 'longText']
    ];

    return $this->createTable($table_name, $fields);
}

remove the table from database

//To delete the tabel from the database

public function removeTable($table_name)
{
    Schema::dropIfExists($table_name); 

    return true;
}

/routes/web.php:

Route::get('/create-table', '[email protected]');

Result

{
   "message": "Good Luck Given table has been successfully created!"
}