From 9e59bbc9f0e8a81ee2ac4f9729cb4045b145fb96 Mon Sep 17 00:00:00 2001 From: Markshall Date: Fri, 24 May 2024 23:00:03 +0100 Subject: [PATCH 1/3] allow a callback to be passed to `updateOrInsert()` to pass different `$values` if the record already exists --- src/Illuminate/Database/Query/Builder.php | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/Illuminate/Database/Query/Builder.php b/src/Illuminate/Database/Query/Builder.php index a2b9b07c5b0..3b09ae8a536 100755 --- a/src/Illuminate/Database/Query/Builder.php +++ b/src/Illuminate/Database/Query/Builder.php @@ -3749,12 +3749,18 @@ public function updateFrom(array $values) * Insert or update a record matching the attributes, and fill it with values. * * @param array $attributes - * @param array $values + * @param \Closure|array $values * @return bool */ - public function updateOrInsert(array $attributes, array $values = []) + public function updateOrInsert(array $attributes, $values = []) { - if (! $this->where($attributes)->exists()) { + $exists = $this->where($attributes)->exists(); + + if ($values instanceof Closure) { + $values = $values($exists); + } + + if (!$exists) { return $this->insert(array_merge($attributes, $values)); } From 14a1a1cebd69c82cf5b200bbbb894ea45fe8e794 Mon Sep 17 00:00:00 2001 From: Markshall Date: Fri, 24 May 2024 23:23:34 +0100 Subject: [PATCH 2/3] follow Laravel codestyle --- src/Illuminate/Database/Query/Builder.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Illuminate/Database/Query/Builder.php b/src/Illuminate/Database/Query/Builder.php index 3b09ae8a536..a108d235cb3 100755 --- a/src/Illuminate/Database/Query/Builder.php +++ b/src/Illuminate/Database/Query/Builder.php @@ -3760,7 +3760,7 @@ public function updateOrInsert(array $attributes, $values = []) $values = $values($exists); } - if (!$exists) { + if (! $exists) { return $this->insert(array_merge($attributes, $values)); } From dbcecb4746d43e256f1255ef22240cdefd24d942 Mon Sep 17 00:00:00 2001 From: Markshall Date: Tue, 28 May 2024 11:59:45 +0100 Subject: [PATCH 3/3] update method signature to add parameter type hinting --- src/Illuminate/Database/Query/Builder.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Illuminate/Database/Query/Builder.php b/src/Illuminate/Database/Query/Builder.php index a108d235cb3..3585c5811b2 100755 --- a/src/Illuminate/Database/Query/Builder.php +++ b/src/Illuminate/Database/Query/Builder.php @@ -3749,10 +3749,10 @@ public function updateFrom(array $values) * Insert or update a record matching the attributes, and fill it with values. * * @param array $attributes - * @param \Closure|array $values + * @param array|callable $values * @return bool */ - public function updateOrInsert(array $attributes, $values = []) + public function updateOrInsert(array $attributes, array|callable $values = []) { $exists = $this->where($attributes)->exists();