@@ -78,21 +78,24 @@ public function primary($columns = null, $name = null, $algorithm = null, $optio
7878 */
7979 public function dropIndex ($ indexOrColumns = null )
8080 {
81- if (is_array ($ indexOrColumns )) {
82- $ indexOrColumns = $ this ->fluent ($ indexOrColumns );
81+ $ indexOrColumns = $ this ->transformColumns ($ indexOrColumns );
8382
84- // Transform the columns to the index name.
85- $ transform = [];
83+ $ this ->collection ->dropIndex ($ indexOrColumns );
8684
87- foreach ($ indexOrColumns as $ column ) {
88- $ transform [$ column ] = $ column . '_1 ' ;
89- }
85+ return $ this ;
86+ }
9087
91- $ indexOrColumns = join ('_ ' , $ transform );
88+ /**
89+ * Indicate that the given index should be dropped, but do not fail if it didn't exist.
90+ *
91+ * @param string|array $indexOrColumns
92+ * @return Blueprint
93+ */
94+ public function dropIndexIfExists ($ indexOrColumns = null )
95+ {
96+ if ($ this ->hasIndex ($ indexOrColumns )) {
97+ $ this ->dropIndex ($ indexOrColumns );
9298 }
93-
94- $ this ->collection ->dropIndex ($ indexOrColumns );
95-
9699 return $ this ;
97100 }
98101
@@ -235,6 +238,41 @@ public function sparse_and_unique($columns = null, $options = [])
235238 return $ this ;
236239 }
237240
241+ /**
242+ * Check whether the given index exists.
243+ *
244+ * @param string|array $indexOrColumns
245+ * @return bool
246+ */
247+ public function hasIndex ($ indexOrColumns = null )
248+ {
249+ $ indexOrColumns = $ this ->transformColumns ($ indexOrColumns );
250+ foreach ($ this ->collection ->listIndexes () as $ index ) {
251+ if ($ index ->getName () == $ indexOrColumns ) {
252+ return true ;
253+ }
254+ }
255+ return false ;
256+ }
257+
258+ /**
259+ * @param string|array $indexOrColumns
260+ * @return string|array
261+ */
262+ private function transformColumns ($ indexOrColumns )
263+ {
264+ if (is_array ($ indexOrColumns )) {
265+ $ indexOrColumns = $ this ->fluent ($ indexOrColumns );
266+ // Transform the columns to the index name.
267+ $ transform = [];
268+ foreach ($ indexOrColumns as $ column ) {
269+ $ transform [$ column ] = $ column . '_1 ' ;
270+ }
271+ $ indexOrColumns = join ('_ ' , $ transform );
272+ }
273+ return $ indexOrColumns ;
274+ }
275+
238276 /**
239277 * Allow fluent columns.
240278 *
0 commit comments