John Davidson

php - Add new column dynamically in table mySQL with Laravel

0 comments
Message:


I have a sensor list form in my program. There the user can do CRUD.
How do when the user enters new sensor data, the new data automatically creates a new column in the table in my database (automatically alter table)


public function store(Request $request){
$data = new Mst_sensor();
$arr = array_merge($arr, ['created_by' => Auth::user()->userid, 'created_at' => date('Y-m-d H:i:s')]);
$data->create($arr);


$sensor= new Trs_sensor_d;
$table = $sensor->getTable();
$columns = \DB::getSchemaBuilder()->getColumnListing($table);

$data_field = [];
foreach ($columns as $k => $v) {
$data_field[$k] = $v;
}
$removed = array_pop($data_field);
$fix_data_field = end($data_field);

$q = "ALTER TABLE `trs_raw_d_gpa` ADD `coba` VARCHAR(25) NULL AFTER '" . $fix_data_field . "'";
}

How can alter table run automatically???



My Answer:
You can use Laravel's Schema Builder to dynamically add a new column to your table when a new sensor data is entered. Here's how you can modify your code to achieve this:

php
public function store(Request $request){
$data = new Mst_sensor();
$arr = array_merge($arr, ['created_by' => Auth::user()->userid, 'created_at' => date('Y-m-d H:i:s')]);
$data->create($arr);

$sensor= new Trs_sensor_d;
$table = $sensor->getTable();
$columns = \DB::getSchemaBuilder()->getColumnListing($table);

$data_field = [];
foreach ($columns as $k => $v) {
$data_field[$k] = $v;
}
$removed = array_pop($data_field);
$fix_data_field = end($data_field);

$new_column_name = 'new_sensor_column'; // You can set the new column name here

if (!in_array($new_column_name, $columns)) {
Schema::table($table, function($table) use ($new_column_name, $fix_data_field) {
$table->string($new_column_name)->nullable()->after($fix_data_field);
});
}
}


In this code snippet, we first check if the new column name already exists in the table columns. If it doesn't exist, we use the Schema Builder to add a new column with the specified name and data type (in this case, a nullable string column). The new column will be added after the last existing column in the table.

Make sure to replace `'new_sensor_column'` with the actual name of the new column you want to add. This way, the table will be automatically altered to include the new column when a new sensor data is entered.

Rate this post

5 of 5 based on 8373 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us