yadakhov/insert-on-duplicate-key
Installation
composer require yadakhov/insert-on-duplicate-key
Add the trait to your Eloquent model:
use Yadakhov\InsertOnDuplicateKey\InsertOnDuplicateKey;
class User extends Model
{
use InsertOnDuplicateKey;
}
First Use Case
Define a unique key (e.g., email) in your migration:
$table->string('email')->unique();
Use insertOnDuplicateKey in your model:
$user = User::insertOnDuplicateKey([
'email' => 'test@example.com',
'name' => 'John Doe',
], [
'name' => 'John Updated', // Fields to update on duplicate
]);
Bulk Inserts with Upserts
$users = [
['email' => 'a@example.com', 'name' => 'Alice'],
['email' => 'b@example.com', 'name' => 'Bob'],
];
User::insertOnDuplicateKey($users, ['name' => 'Updated']);
Conditional Updates Use closures for dynamic updates:
$user = User::insertOnDuplicateKey([
'email' => 'test@example.com',
'active' => false,
], function ($attributes) {
return ['active' => true]; // Only update if duplicate
});
Integration with Queues Queue jobs for delayed upserts:
User::dispatchSyncOnDuplicateKey([
'email' => 'test@example.com',
'name' => 'John',
], ['name' => 'John']);
collect($users)->each(function ($user) {
User::insertOnDuplicateKey($user, ['last_updated' => now()]);
});
return response()->json(
User::insertOnDuplicateKey($data, $updates)
);
Unique Key Mismatch
ON DUPLICATE KEY UPDATE fields match the unique/primary key constraints.\DB::enableQueryLog();
User::insertOnDuplicateKey(...);
dd(\DB::getQueryLog());
Closure Evaluation
Mass Assignment
$fillable or $guarded to prevent unintended updates.try {
User::insertOnDuplicateKey($data, $updates);
} catch (\Illuminate\Database\QueryException $e) {
// Handle validation errors
}
Custom Query Builder Extend the trait for raw queries:
use Yadakhov\InsertOnDuplicateKey\InsertOnDuplicateKey as BaseTrait;
class CustomInsertOnDuplicateKey extends BaseTrait {
public function customUpsert($data, $updates) {
return \DB::table('users')->insertOnDuplicateKey($data, $updates);
}
}
Event Hooks
Listen for eloquent.saving to modify updates dynamically:
User::saved(function ($model) {
if ($model->wasRecentlyCreated) {
// Post-upsert logic
}
});
Soft Deletes
Override getKeyName() if using soft deletes:
protected $primaryKey = 'id';
public function getKeyName() { return 'deleted_at'; } // Custom logic
How can I help you explore Laravel packages today?