@@ -78,21 +78,24 @@ public function primary($columns = null, $name = null, $algorithm = null, $optio
78
78
*/
79
79
public function dropIndex ($ indexOrColumns = null )
80
80
{
81
- if (is_array ($ indexOrColumns )) {
82
- $ indexOrColumns = $ this ->fluent ($ indexOrColumns );
81
+ $ indexOrColumns = $ this ->transformColumns ($ indexOrColumns );
83
82
84
- // Transform the columns to the index name.
85
- $ transform = [];
83
+ $ this ->collection ->dropIndex ($ indexOrColumns );
86
84
87
- foreach ($ indexOrColumns as $ column ) {
88
- $ transform [$ column ] = $ column . '_1 ' ;
89
- }
85
+ return $ this ;
86
+ }
90
87
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 );
92
98
}
93
-
94
- $ this ->collection ->dropIndex ($ indexOrColumns );
95
-
96
99
return $ this ;
97
100
}
98
101
@@ -235,6 +238,41 @@ public function sparse_and_unique($columns = null, $options = [])
235
238
return $ this ;
236
239
}
237
240
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
+
238
276
/**
239
277
* Allow fluent columns.
240
278
*
0 commit comments