Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To create a new column in Laravel based on the values found in an existing column, you can use the Laravel migration feature. Here are the steps to follow:

  1. Run the following command to create a new migration file:

    php artisan make:migration add_new_column_to_table --table=your_table_name
    
  2. Open the newly created migration file in the database/migrations folder and add the following code to the up function:

    Schema::table('your_table_name', function (Blueprint $table) {
       $table->string('new_column_name')->nullable()->after('existing_column_name');
       foreach (\App\YourModel::all() as $row) {
           $row->new_column_name = $row->existing_column_name . '_new';
           $row->save();
       }
    });
    

    This code will add a new nullable string column named new_column_name to the your_table_name table, and then iterate through all the rows in the your_table_name table to update the new_column_name column with a new value based on the value in the existing_column_name.

  3. To run the migration, run the following command:

    php artisan migrate
    

    This will apply the changes to your database schema.

  4. Now you can retrieve the values from the new column in your model using the new_column_name attribute as you would with any other column.

Note: If you want to roll back the migration, simply run the following command:

php artisan migrate:rollback