@@ -71,6 +71,7 @@ class Builder extends BaseEloquentBuilder
7171 'bucketaggregation ' ,
7272 'openpit ' ,
7373 'bulkinsert ' ,
74+ 'createonly ' ,
7475 ];
7576
7677 /**
@@ -95,7 +96,7 @@ public function setModel($model): static
9596 public function newModelInstance ($ attributes = [])
9697 {
9798 $ model = $ this ->model ->newInstance ($ attributes )->setConnection (
98- $ this ->query ->getConnection () ->getName ()
99+ $ this ->query ->connection ->getName ()
99100 );
100101
101102 // Merge in our options.
@@ -216,7 +217,7 @@ public function hydrate(array $items)
216217 $ instance = $ this ->newModelInstance ();
217218
218219 return $ instance ->newCollection (array_map (function ($ item ) use ($ instance ) {
219- return $ instance ->newFromBuilder ($ item , $ this ->getConnection () ->getName ());
220+ return $ instance ->newFromBuilder ($ item , $ this ->query -> connection ->getName ());
220221 }, $ items ));
221222 }
222223
@@ -394,6 +395,17 @@ public function withoutRefresh()
394395 return $ this ->model ;
395396 }
396397
398+ /**
399+ * Explicitly control the Elasticsearch refresh behavior for write ops.
400+ * Accepts: true, false, or 'wait_for'.
401+ */
402+ public function withRefresh (bool |string $ refresh ): static
403+ {
404+ $ this ->query ->options ()->add ('refresh ' , $ refresh );
405+
406+ return $ this ;
407+ }
408+
397409 /**
398410 * @throws DynamicIndexException
399411 */
@@ -644,6 +656,27 @@ public function rawDsl($dsl): array
644656 return $ this ->query ->raw ($ dsl )->asArray ();
645657 }
646658
659+ /**
660+ * Force insert operations to use op_type=create for dedupe semantics.
661+ * When set, attempts to create an existing _id will fail with a 409 from Elasticsearch.
662+ */
663+ public function createOnly (): static
664+ {
665+ // mark insert op type on the underlying query options
666+ $ this ->query ->options ()->add ('insert_op_type ' , 'create ' );
667+
668+ return $ this ;
669+ }
670+
671+ /**
672+ * Convenience method to perform a create-only insert and surface 409s as exceptions.
673+ * Accepts single document attributes or an array of documents.
674+ */
675+ public function createOrFail (array $ attributes )
676+ {
677+ return $ this ->createOnly ()->create ($ attributes );
678+ }
679+
647680 // ----------------------------------------------------------------------
648681 // Protected
649682 // ----------------------------------------------------------------------
0 commit comments