2022_06_02_081655_referral_code.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. use App\Models\User;
  3. use App\Traits\Referral;
  4. use Illuminate\Database\Migrations\Migration;
  5. use Illuminate\Database\Schema\Blueprint;
  6. use Illuminate\Support\Facades\DB;
  7. use Illuminate\Support\Facades\Schema;
  8. use Illuminate\Support\Str;
  9. return new class extends Migration
  10. {
  11. use Referral;
  12. public function setReferralCode($userid)
  13. {
  14. $code = $this->createReferralCode();
  15. DB::table('users')
  16. ->where('id', '=', $userid)
  17. ->update(['referral_code' => $code]);
  18. }
  19. /**
  20. * Run the migrations.
  21. *
  22. * @return void
  23. */
  24. public function up()
  25. {
  26. Schema::table('users', function (Blueprint $table) {
  27. $table->string('referral_code')->lenght(8)->nullable();
  28. });
  29. $existing_user = User::where('referral_code', '')->orWhere('referral_code', null)->get();
  30. foreach ($existing_user as $user) {
  31. $this->setReferralCode($user->id);
  32. }
  33. }
  34. /**
  35. * Reverse the migrations.
  36. *
  37. * @return void
  38. */
  39. public function down()
  40. {
  41. Schema::table('users', function (Blueprint $table) {
  42. $table->dropColumn('referral_code');
  43. });
  44. }
  45. };