logo
down
shadow

With Laravel Migration, How to change data type of a column and update its existing data to fit the new data type, witho


With Laravel Migration, How to change data type of a column and update its existing data to fit the new data type, witho

By : user2951283
Date : November 18 2020, 01:01 AM
will help you Suppose I have a users table which has been created through Migration and Schema Builder, like this: , Here is how I performed this:
The up() method:
code :
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    // do the following steps in order:
    // 1- add a new column with the desired data type to the table
    // 2- fill the new column with the appropriate data
    // 3- delete the old column
    // 4- rename the new column to match name of the deleted column

    Schema::table('users', function(Blueprint $table)
    {
        // 1- add a new column with the desired data type to the table
        // note that after() method is used to order the column and works only with MySQL
        $table->boolean('is_suspended_new')->default(0)->after('is_suspended');
    });

    // 2- fill the new column with the appropriate data 
    // note that you may need to use data in the old column as a guide (like in this example)
    $users = User::all();
    if ($users) {
        foreach ($users as $user) {
            $u = User::find($user->id);

            if ($u->is_suspended === 'yes') {
                $u->is_suspended_new = 1;
            } elseif ($u->is_suspended === 'no') {
                $u->is_suspended_new = 0;
            }

            $u->save();
        }
    }

    Schema::table('users', function(Blueprint $table)
    {
        // 3- delete the old column
        $table->dropColumn('is_suspended');
    });

    Schema::table('users', function(Blueprint $table)
    {
        // 4- rename the new column to match name of the deleted column
        $table->renameColumn('is_suspended_new', 'is_suspended');
    });
}
/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    // IMPORTANT NOTE:
    // because renaming (enum) column types is not supported in laravel 4.2 (as mentioned here http://goo.gl/zU7zvw)
    // so we will make some changes in the order of the steps as follows:
    // 
    // do the following steps in order:
    // 1- rename the exiting column
    // 2- add a new column with the desired data type and give it a name matches name of the existing column before renaming
    // 3- fill the new column with the appropriate data
    // 4- delete the old column

    Schema::table('users', function(Blueprint $table)
    {
        // 1- rename the existing column
        $table->renameColumn('is_suspended', 'is_suspended_old');
    });

    Schema::table('users', function(Blueprint $table)
    {
        // 2- add a new column with the desired data type to the table
        // and give it a name matches name of the existing column before renaming
        // note that after() method is used to order the column and works only with MySQL
        $table->enum('is_suspended', ['yes', 'no'])->default('no')->after('is_suspended_old');
    });

    // 3- fill the new column with the approprite data 
    // note that you may need to use data in the old column as a guide (like in this example)
    $users = User::all();
    if ($users) {
        foreach ($users as $user) {
            $u = User::find($user->id);

            if ($u->is_suspended_old == 1) {
                $u->is_suspended = 'yes';
            } elseif ($u->is_suspended_old == 0) {
                $u->is_suspended = 'no';
            }

            $u->save();
        }
    }

    Schema::table('users', function(Blueprint $table)
    {
        // 4- delete the old column
        $table->dropColumn('is_suspended_old');
    });
}


Share : facebook icon twitter icon
Rails migration: change column data type from date to integer

Rails migration: change column data type from date to integer


By : Melissa
Date : March 29 2020, 07:55 AM
I hope this helps . I disagree with the other posters: you are better off storing the year as an integer if that is truly the information you want to capture. Because if you don't, and store a full date, then you're actually storing a piece of information that's a misrepresentation. I.e., it's storing a day and month and possibly some calendar metadata as well. Every time you use it you'll need to keep this in mind, and make sure that any calculations are what you really want to be doing. I.e., there are many Date and Time classes and libraries, all in use, all within Rails and Ruby.
If you only need and want the year, then store just the year. To achieve this, I'd go the easy and conservative route: make several simple migrations.
Core Data Migration: How should i change the data type from bool to int in next version

Core Data Migration: How should i change the data type from bool to int in next version


By : user3236165
Date : March 29 2020, 07:55 AM
Any of those help didn't try but since BOOL and int are both internally saved as NSNumber's, lightweight migrations should work.
How to change data type and add column with migration without losing data? (laravel 5.3)

How to change data type and add column with migration without losing data? (laravel 5.3)


By : Sushant
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further My migration is like this : , Create a new migration file using below command :
code :
php artisan make:migration name_of_your_file
    public function up()
        {
            Schema::table('tests', function($table) {
                  $table->renameColumn('id_test', 'id');
                  $table->string('id_test', 18);
            });
        }


   public function down()
        {
            Schema::table('tests', function($table) {
                 $table->dropColumn('id_test');
            });
        }
php artisan migrate
Rails migration : Change column type and update existing data

Rails migration : Change column type and update existing data


By : user2443064
Date : March 29 2020, 07:55 AM
To fix this issue I am using Postgres. Not sure whether this solution works for other databases. people table used as an example - do not forget to change the table name to your own.
code :
  def up
    change_column :people, :permanent, 'integer USING CAST(permanent AS integer)'
    Person.connection.execute("UPDATE people SET permanent = CASE permanent WHEN 0 THEN 1 WHEN 1 THEN 2 END")
  end

  def down
    Person.connection.execute("UPDATE people SET permanent = CASE permanent WHEN 1 THEN 0 WHEN 2 THEN 1 END")
    change_column :people, :permanent, 'boolean USING CAST(permanent AS boolean)'
  end
Laravel Migration - Data type also changes when renaming column

Laravel Migration - Data type also changes when renaming column


By : Banning_man
Date : March 29 2020, 07:55 AM
I wish this helpful for you I learned that there is an issue in Schema regarding the enum and still in discussion until now. I just used the other way to update the datatype of the column.
code :
DB::statement('ALTER TABLE reservations MODIFY COLUMN payment_amount_full double(10,2)');
Related Posts Related Posts :
  • PHP - Prevent client from tampering the ID of a form
  • unexpected T_PUBLIC error
  • Types of testcases in PHPUnit
  • keeping a LDAP user logged in with PHP session
  • Detect if browser supports WebP format? (server side)
  • real_escape_string not cleaning up entered text
  • E-commerce products filter
  • Why having more than one test method in a file using Laravel raises error?
  • PHP Escaped special characters to html
  • Basic prepared statement not INSERTING
  • PHP combobox not showing in HTML table
  • MySql PHP row request to variable
  • Join two tables with one table has multiple rows matching
  • Looping through users with Instagram API requests is REALLY slow
  • Unable to add 30 days to date within loop
  • Return from mysqli_query() into array
  • php rename() function returns "No such file or directory" error
  • form submit inside navigation menu
  • PHP: reasons to use GET and POST request at the same time?
  • Is break; required after die() php
  • little depth of session in php
  • Authentication Logon page not working using PHP and Oracle on Apache / Windows 2008
  • Magento reindexing error product flat data
  • Laravel 4: Running composer when deploying to Heroku
  • Long Polling or WebSockets
  • How to use mysqli_stmt_bind_param for integers, boolean, etc
  • Determining the content of a link
  • MYSQL and PHP update events?
  • PHP explode all square bracket
  • Transparent hexagon-masked collage using PHP GD
  • Plugins or text do NOT show up on custom wordpress template
  • inserting data into mysqli database
  • Two arguments to closure function laravel
  • UnClear image exported by ffmpeg from mp4 file
  • is the time of computer and localhost same?
  • change custom data- value after ajax post success
  • Can We Restrict PHP Variables to accept only certain type of values
  • csv file is inserting a blank row in the last of other rows into mysql table
  • How to convert special characters in xml using php?
  • Mcrypt are very confusing
  • Dynamic image for user's ID
  • How to only upload specific parts of HTML form with PHP?
  • Dynamic PHP string as MySQL table name
  • What is the error in my query?
  • PHP Upstart on Amazon EC2 Linux (Elasticbeanstalk)
  • how to print dynamic variable value in php
  • php mysql insert values and select
  • uploading image in codeigniter controller
  • Converting htaccess to nginx for counter
  • how can I show my signal transaction data as project name
  • php raspberry pi trying to change pi date
  • PHP and mysql, SELECT query return null
  • Unable to store Date values in php mysql table that are existing in excel file
  • Can we include 2 Mail() functions in 1 Page?
  • Problems with chinese characters
  • How to apply a function to every foreach result?
  • Use of CONCAT in FROM clause
  • Tag endpoint combined with user endpoint with Instagram API
  • create dynamic time in php and mysql
  • How to break zero index comma separated value into individual string in php
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org