trifek's avatar

Problem with registered new user when old was deleted

Hi, I have this code:

Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('company_id')->unsigned();
            $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
            $table->string('name');
            $table->string('surname')->nullable();
            $table->mediumText('description')->nullable();
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->boolean('enable')->default(false);
            $table->string('slug', 250);
            $table->rememberToken();
            $table->softDeletes();
            $table->timestamps();
        });

When I create new user or delete this user this migration work fine. Problem is when I soft deleted user ex [email protected] and then I try create new user [email protected] (when old was deleted).

My code to create to save user:

$validator = Validator::make(['email' => $adult->email],[
                    'email' => 'unique:users,email,NULL,id,deleted_at,NULL'
                ]);
                if($validator->passes()){
                   /// codę to creation user
                }
                else{
                   echo 'This user exist';
                }

When I run my code I have error:

"message": "SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '[email protected]' for key 'users.users_email_unique' (Connection: mysql, SQL: insert into `users` (`name`, `surname`, `email`, `enable`, `password`, `email_verified_at`, `company_id`, `slug`, `updated_at`, `created_at`) values (\u0141ukasz, XXXX, [email protected], 1, /Tzqaigb0jSadFH8xJYqu, 2024-04-10 16:15:07, 1, xxxx-6, 2024-04-10 16:15:07, 2024-04-10 16:15:07))",
    "exception": "Illuminate\Database\UniqueConstraintViolationException"

How can I repair it? Please help me :)

0 likes
6 replies
tykus's avatar

If you do not intend to reuse(/restore) the original record for the "new" user, and you want to maintain soft-deletes on the Model, then you need to change the original record's email address. You can use model events to hook into the deleting event where you change the email address of the record being deleted (e.g. [email protected] is updated to [email protected]):

// User Model
protected static function booted(): void
{
    static::deleting(function (User $user) {
        $user->update(['email' => str($user->email)->prepend('__deleted__')]);
    });
}

Now, the soft-deleted record has a different email (but still can be mapped to its original value) and your "new" User can use the same email address.

trifek's avatar

Im copy yours code to my User.php (model), but it's not working. When I deleted user - I haven't update to [email protected] :(

trifek's avatar
User::where('id', $id)->delete();
tykus's avatar
tykus
Best Answer
Level 104

@trifek that code is not going to fire the deleting event because you never have a Model instance that can fire the event - instead you remain in Builder land:

// get a Model instance
$user = User::find(OrFail$id);
$user->delete();
1 like
trifek's avatar

Thank you. This is working :)

Please or to participate in this conversation.