Laravel MongoDB
This is my Store()
method in UserController
:
public function store()
{
$userData = request()->get('user', []);
.
.
//Checking if credentials satisfied
.
.
try
{
$user = User::create($userData);
}
catch(BulkWriteException $ex)
{
abort(409, trans('errors.EXISTS_USERNAME'));
}
catch(Exception $e)
{
abort(409, trans('errors.EXISTS_USERNAME'));
}
return [
'status' => 'success',
'result' => $user,
];
}
Close up to the Create() method in the above Code:
public static function create($parameters)
{
return static::query()->create($parameters);
}
Close up to the Create() method in the above Code:
public function create(array $attributes = [])
{
return tap($this->newModelInstance($attributes), function ($instance) {
$instance->save();
});
}
So the problem is When I delete a User
for example with username: "X"
I can't make a new User
with username: "X"
and it gives the error u see in the exception.
The deletion method is soft-delete which means the user not completely deleted from DB it just gives the user deleted_at
property so laravel will understand that act to this user like a deleted user which means when I use a query like User::where('username',"X")->get()
it won't show me any result which means the data is deleted.
so here's the deal, I can't understand why it throws me exception about Existing Username
while laravel can't see the user as a data.
What I want to do is fixing this issue without using force-delete and with only using soft-delete
CodePudding user response:
You note that your username is a unique field.
You are using Laravel soft-deletes.
This means that Laravel keeps the record in the database, and places a non-null value inside deleted_at
within your users table.
Because the data is not deleted from the database, the database cannot create a new record with the same name "X", because that record "X" already exists -- it just appears deleted to Laravel due to the soft delete.
If you want the protection of a unique user name, this is not a problem: it is working correctly by preventing you from duplicating a username
against ALL users ever, even those you have had to delete. You may need to keep the user data over time (thus the soft-delete), and this would successfully prevent you from duplicating even an old 'removed' user. If you don't want this protection, remove the unique field from the username
.