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