Skip to content

Instantly share code, notes, and snippets.

@mikebronner
Last active September 29, 2016 16:40
Show Gist options
  • Save mikebronner/72288dc0260e292381ad6e08bf481d0b to your computer and use it in GitHub Desktop.
Save mikebronner/72288dc0260e292381ad6e08bf481d0b to your computer and use it in GitHub Desktop.
MIgrate Laravel Cashier from 5.x to 6.x/7.x (Be sure to test before running on production!)
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddStripeFieldsAndTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function ($table) {
$table->string('card_brand')->nullable();
$table->string('card_last_four')->nullable();
});
Schema::create('subscriptions', function ($table) {
$table->increments('id');
$table->integer('user_id');
$table->string('name');
$table->string('stripe_id');
$table->string('stripe_plan');
$table->integer('quantity');
$table->timestamp('trial_ends_at')->nullable();
$table->timestamp('ends_at')->nullable();
$table->timestamps();
});
DB::statement(DB::raw("
UPDATE users
SET card_last_four = last_four
"));
DB::statement(DB::raw("
INSERT INTO subscriptions
(user_id, name, stripe_id, stripe_plan, quantity, trial_ends_at, ends_at, created_at, updated_at)
SELECT id, 'membership', stripe_subscription, stripe_plan, '1', trial_ends_at, subscription_ends_at, created_at, updated_at
FROM users
WHERE users.stripe_subscription IS NOT NULL
AND users.stripe_active = '1'
"));
Schema::table('users', function (Blueprint $table) {
$table->dropColumn(
'stripe_active',
'stripe_subscription',
'stripe_plan',
'trial_ends_at',
'subscription_ends_at',
'last_four'
);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function ($table) {
$table->boolean('stripe_active')->default(0);
$table->string('stripe_subscription')->nullable();
$table->string('stripe_plan', 100)->nullable();
$table->string('last_four', 4)->nullable();
$table->dateTime('trial_ends_at')->nullable();
$table->dateTime('subscription_ends_at')->nullable();
});
DB::statement(DB::raw("
UPDATE users
SET last_four = card_last_four
"));
DB::statement(DB::raw("
UPDATE users
SET stripe_plan = subscriptions.stripe_plan,
trial_ends_at = subscriptions.trial_ends_at,
subscription_ends_at = subscriptions.ends_at,
created_at = subscriptions.created_at,
updated_at = subscriptions.updated_at
FROM subscriptions
WHERE subscriptions.user_id = users.id
"));
Schema::table('users', function (Blueprint $table) {
$table->dropColumn([
'card_brand',
'card_last_four',
]);
});
Schema::drop('subscriptions');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment