70208d2157
Shift automatically applies the Laravel coding style - which uses the PSR-12 coding style as a base with some minor additions. You may customize the code style applied by configuring [Pint](https://laravel.com/docs/pint), [PHP CS Fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer), or [PHP CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer) for your project root. For more information on customizing the code style applied by Shift, [watch this short video](https://laravelshift.com/videos/shift-code-style).
54 lines
1.3 KiB
PHP
54 lines
1.3 KiB
PHP
<?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)
|
|
->update(['referral_code' => $random]);
|
|
} else {
|
|
$this->generateCode($userid);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 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();
|
|
|
|
foreach ($existing_user as $user) {
|
|
$this->generateCode($user->id);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Reverse the migrations.
|
|
*
|
|
* @return void
|
|
*/
|
|
public function down()
|
|
{
|
|
Schema::table('users', function (Blueprint $table) {
|
|
$table->dropColumn('referral_code');
|
|
});
|
|
}
|
|
}
|