]> BookStack Code Mirror - bookstack/blob - database/migrations/2021_03_08_215138_add_user_slug.php
c0e1313a714a05d46324584ba6fd605547a14f75
[bookstack] / database / migrations / 2021_03_08_215138_add_user_slug.php
1 <?php
2
3 use Illuminate\Database\Migrations\Migration;
4 use Illuminate\Database\Schema\Blueprint;
5 use Illuminate\Support\Facades\Schema;
6 use Illuminate\Support\Str;
7
8 return new class extends Migration
9 {
10     /**
11      * Run the migrations.
12      *
13      * @return void
14      */
15     public function up()
16     {
17         Schema::table('users', function (Blueprint $table) {
18             $table->string('slug', 180);
19         });
20
21         $slugMap = [];
22         DB::table('users')->cursor()->each(function ($user) use (&$slugMap) {
23             $userSlug = Str::slug($user->name);
24             while (isset($slugMap[$userSlug])) {
25                 $userSlug = Str::slug($user->name . Str::random(4));
26             }
27             $slugMap[$userSlug] = true;
28
29             DB::table('users')
30                 ->where('id', $user->id)
31                 ->update(['slug' => $userSlug]);
32         });
33
34         Schema::table('users', function (Blueprint $table) {
35             $table->unique('slug');
36         });
37     }
38
39     /**
40      * Reverse the migrations.
41      *
42      * @return void
43      */
44     public function down()
45     {
46         Schema::table('users', function (Blueprint $table) {
47             $table->dropColumn('slug');
48         });
49     }
50 };