ctrlpanel/database/migrations/2022_06_02_081655_referral_code.php

54 lines
1.3 KiB
PHP
Raw Normal View History

2022-06-02 14:11:24 +00:00
<?php
use App\Models\User;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
class ReferralCode extends Migration
{
public function generateCode($userid)
{
$random = STR::random(8);
if (User::where('referral_code', '=', $random)->doesntExist()) {
DB::table('users')
->where('id', '=', $userid)
2022-06-07 08:18:33 +00:00
->update(['referral_code' => $random]);
} else {
$this->generateCode($userid);
}
2022-06-07 08:18:33 +00:00
}
2022-06-02 14:11:24 +00:00
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('referral_code')->lenght(8)->nullable();
});
$existing_user = User::where('referral_code', '')->orWhere('referral_code', null)->get();
2022-06-02 14:11:24 +00:00
foreach ($existing_user as $user) {
2022-06-07 08:18:33 +00:00
$this->generateCode($user->id);
2022-06-02 14:11:24 +00:00
}
}
2022-06-02 14:11:24 +00:00
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('referral_code');
});
}
}