Refactor firstOrCreate
to include soft deleted models
#48799
Unanswered
chrisloftus
asked this question in
Ideas
Replies: 2 comments
-
the solution is there already
\Illuminate\Database\Eloquent\SoftDeletingScope::addRestoreOrCreate |
Beta Was this translation helpful? Give feedback.
0 replies
-
The other option would be to make the field semi unique: <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('email')->check();
$table->boolean('ucode')->virtualAs("CASE WHEN deleted_at IS NULL THEN b'1' ELSE NULL END")
$table->unique([ 'ucode', 'email' ]);
$table->softDeletes();
$table->timestamps();
});
}
}; |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I recently ran into a bug where I had a model which uses soft deletes and some simple code like:
This was causing unique constraint errors at the database level when a user had previously been soft deleted as
firstOrCreate
doesn't take into account soft deletes (/withTrashed()
).I had to refactor the code to a much less elegant way:
I am willing to PR this, potentially by making the following work, if people are open to it?
Thanks.
Beta Was this translation helpful? Give feedback.
All reactions