Overview
Laravel provides a facade to access the schema builder class Schema,
which lets you create and modify tables, or collections in MongoDB.
Facades are static interfaces to classes that make the syntax more
concise and improve testability.
The Laravel Integration supports a subset of the index and collection management methods
in the Laravel Schema facade.
To learn more about facades, see Facades in the Laravel documentation.
The following sections describe the Laravel schema builder features available in the Laravel Integration and show examples of how to use them:
Perform Laravel Migrations
Laravel migrations let you programmatically create, modify, and delete
your database schema by running methods included in the Schema facade.
The following sections explain how to author a migration class when you use
a MongoDB database and how to run them.
Modifying databases and collections from within a migration provides a controlled approach that ensures consistency, version control, and reversibility in your application.
Create a Migration Class
You can create migration classes manually or generate them by using the
php artisan make:migration command. If you generate them, you must make the
following changes to perform the schema changes on your MongoDB database:
- Replace the - Illuminate\Database\Schema\Blueprintimport with- MongoDB\Laravel\Schema\Blueprintif it is referenced in your migration
- Use only commands and syntax supported by the Laravel Integration 
Tip
If your default database connection is set to anything other than your MongoDB database, update the following setting to make sure the migration specifies the correct database:
- Make sure your - connectionsarray item contains a valid- mongodbentry in your- config/database.phpfile
- Specify - "mongodb"in the- $connectionfield of your migration class
The following example migration class contains the following methods:
- up(), which creates a collection and an index when you run the migration
- down(), which drops the collection and all the indexes on it when you roll back the migration
declare(strict_types=1); use Illuminate\Database\Migrations\Migration; use Illuminate\Support\Facades\Schema; use MongoDB\Laravel\Schema\Blueprint; return new class extends Migration {     protected $connection = 'mongodb';     /**      * Run the migrations.      */     public function up(): void     {         Schema::create('astronauts', function (Blueprint $collection) {             $collection->index('name');         });     }     /**      * Reverse the migrations.      */     public function down(): void     {         Schema::drop('astronauts');     } }; 
Run or Roll Back a Migration
To run the database migration from a class file, run the following command after replacing the placeholder:
php artisan migrate --path=<path to your migration class file> 
This command runs the up() function in the class file to create the
collection and index in the database specified in the config/database.php
file.
To roll back the migration, run the following command after replacing the placeholder:
php artisan migrate:rollback --path=<path to your migration class file> 
This command runs the down() function in the class file to drop the
collection and related indexes.
To learn more about Laravel migrations, see Database: Migrations in the Laravel documentation.
Implement Schema Validation
Starting in Laravel Integration v5.5, you can use the jsonSchema() method
to implement schema validation when
using the following schema builder methods:
- Schema::create(): When creating a new collection
- Schema::table(): When updating collection properties
You can use schema validation to restrict data types and value ranges of document fields in a specified collection. After you implement schema validation, the server restricts write operations that don't follow the validation rules.
You can pass the following parameters to jsonSchema():
- schema: Array that specifies the validation rules for the collection. To learn more about constructing a schema, see the $jsonSchema reference in the Server manual.
- validationLevel: Sets the level of validation enforcement. Accepted values are- "strict"(default) and- "moderate".
- validationAction: Specifies the action to take when invalid operations are attempted. Accepted values are- "error"(default) and- "warn".
This example demonstrates how to specify a schema in the
jsonSchema() method when creating a collection. The schema
validation has the following specifications:
- Documents in the - pilotscollection must contain the- license_numberfield.
- The - license_numberfield must have an integer value between- 1000and- 9999.
- If you attempt to perform invalid write operations, the server raises an error. 
Schema::create('pilots', function (Blueprint $collection) {     $collection->jsonSchema(         schema: [             'bsonType' => 'object',             'required' => ['license_number'],             'properties' => [                 'license_number' => [                     'bsonType' => 'int',                     'minimum' => 1000,                     'maximum' => 9999,                 ],             ],         ],         validationAction: 'error',     ); }); 
If you attempt to insert a document into the pilots collection that
violates the schema validation rule, Laravel MongoDB returns a
BulkWriteException.
Check Whether a Collection Exists
To check whether a collection exists, call the hasCollection() method on
the Schema facade in your migration file. You can use this to
perform migration logic conditionally.
The following example migration creates a telescopes collection if a collection
named stars exists:
$hasCollection = Schema::hasCollection('stars'); if ($hasCollection) {     Schema::create('telescopes'); } 
Manage Indexes
MongoDB indexes are data structures that improve query efficiency by reducing the number of documents needed to retrieve query results. Certain indexes, such as geospatial indexes, extend how you can query the data.
To improve query performance by using an index, make sure the index covers the query. To learn more about indexes and query optimization, see the following Server manual entries:
The following sections show how you can use the schema builder to create and drop various types of indexes on a collection.
Create an Index
To create indexes, perform the following actions:
- Call the - create()method on the- Schemafacade in your migration file.
- Pass it the collection name and a callback method with a - MongoDB\Laravel\Schema\Blueprintparameter.
- Specify the index creation details on the - Blueprintinstance.
The following example migration creates indexes on the following collection fields:
- Single field index on - mission_type
- Compound index on - launch_locationand- launch_date, specifying a descending sort order on- launch_date
- Unique index on the - mission_idfield, specifying the index name- "unique_mission_id_idx"
Click the VIEW OUTPUT button to see the indexes created by running
the migration, including the default index on the _id field:
Schema::create('flights', function (Blueprint $collection) {     $collection->index('mission_type');     $collection->index(['launch_location' => 1, 'launch_date' => -1]);     $collection->unique('mission_id', options: ['name' => 'unique_mission_id_idx']); }); 
[   { v: 2, key: { _id: 1 }, name: '_id_' },   { v: 2, key: { mission_type: 1 }, name: 'mission_type_1' },   {     v: 2,     key: { launch_location: 1, launch_date: -1 },     name: 'launch_location_1_launch_date_-1'   },   {     v: 2,     key: { mission_id: 1 },     name: 'unique_mission_id_idx',     unique: true   } ] 
Specify Index Options
MongoDB index options determine how the indexes are used and stored.
You can specify index options when calling an index creation method, such
as index(), on a Blueprint instance.
The following migration code shows how to add a collation to an index as an
index option. Click the VIEW OUTPUT button to see the indexes
created by running the migration, including the default index on the _id
field:
Schema::create('passengers', function (Blueprint $collection) {     $collection->index(         'last_name',         name: 'passengers_collation_idx',         options: [             'collation' => [ 'locale' => 'de@collation=phonebook', 'numericOrdering' => true ],         ],     ); }); 
[   { v: 2, key: { _id: 1 }, name: '_id_' },   {     v: 2,     key: { last_name: 1 },     name: 'passengers_collation_idx',     collation: {       locale: 'de@collation=phonebook',       caseLevel: false,       caseFirst: 'off',       strength: 3,       numericOrdering: true,       alternate: 'non-ignorable',       maxVariable: 'punct',       normalization: false,       backwards: false,       version: '57.1'     }   } ] 
To learn more about index options, see Options for All Index Types in the Server manual.
Create Sparse, TTL, and Unique Indexes
You can use Laravel MongoDB helper methods to create the following types of indexes:
- Sparse indexes, which allow index entries only for documents that contain the specified field 
- Time-to-live (TTL) indexes, which expire after a set amount of time 
- Unique indexes, which prevent inserting documents that contain duplicate values for the indexed field 
To create these index types, perform the following actions:
- Call the - create()method on the- Schemafacade in your migration file.
- Pass - create()the collection name and a callback method with a- MongoDB\Laravel\Schema\Blueprintparameter.
- Call the appropriate helper method for the index type on the - Blueprintinstance and pass the index creation details.
The following migration code shows how to create a sparse and a TTL index
by using the index helpers. Click the VIEW OUTPUT button to see
the indexes created by running the migration, including the default index on
the _id field:
Schema::create('planets', function (Blueprint $collection) {     $collection->sparse('rings');     $collection->expire('last_visible_dt', 86400); }); 
[   { v: 2, key: { _id: 1 }, name: '_id_' },   { v: 2, key: { rings: 1 }, name: 'rings_1', sparse: true },   {     v: 2,     key: { last_visible_dt: 1 },     name: 'last_visible_dt_1',     expireAfterSeconds: 86400   } ] 
You can specify sparse, TTL, and unique indexes on either a single field or compound index by specifying them in the index options.
The following migration code shows how to create all three types of indexes
on a single field. Click the VIEW OUTPUT button to see the indexes
created by running the migration, including the default index on the _id
field:
Schema::create('planet_systems', function (Blueprint $collection) {     $collection->index('last_visible_dt', options: ['sparse' => true, 'expireAfterSeconds' => 3600, 'unique' => true]); }); 
[   { v: 2, key: { _id: 1 }, name: '_id_' },   {     v: 2,     key: { last_visible_dt: 1 },     name: 'last_visible_dt_1',     unique: true,     sparse: true,     expireAfterSeconds: 3600   } ] 
To learn more about these indexes, see Index Properties in the Server manual.
Create a Geospatial Index
In MongoDB, geospatial indexes let you query geospatial coordinate data for inclusion, intersection, and proximity.
To create geospatial indexes, perform the following actions:
- Call the - create()method on the- Schemafacade in your migration file.
- Pass - create()the collection name and a callback method with a- MongoDB\Laravel\Schema\Blueprintparameter.
- Specify the geospatial index creation details on the - Blueprintinstance.
The following example migration creates a 2d and 2dsphere geospatial
index on the spaceports collection. Click the VIEW OUTPUT
button to see the indexes created by running the migration, including the
default index on the _id field:
Schema::create('spaceports', function (Blueprint $collection) {     $collection->geospatial('launchpad_location', '2dsphere');     $collection->geospatial('runway_location', '2d'); }); 
[   { v: 2, key: { _id: 1 }, name: '_id_' },   {     v: 2,     key: { launchpad_location: '2dsphere' },     name: 'launchpad_location_2dsphere',     '2dsphereIndexVersion': 3   },   { v: 2, key: { runway_location: '2d' }, name: 'runway_location_2d' } ] 
To learn more about geospatial indexes, see Geospatial Indexes in the Server manual.
Drop an Index
To drop indexes from a collection, perform the following actions:
- Call the - table()method on the- Schemafacade in your migration file.
- Pass it the table name and a callback method with a - MongoDB\Laravel\Schema\Blueprintparameter.
- Call the - dropIndex()method with the index name on the- Blueprintinstance.
Note
If you drop a collection, MongoDB automatically drops all the indexes associated with it.
The following example migration drops an index called unique_mission_id_idx
from the flights collection:
Schema::table('flights', function (Blueprint $collection) {     $collection->dropIndex('unique_mission_id_idx'); }); 
Manage MongoDB Search and MongoDB Vector Search Indexes
In MongoDB, MongoDB Search indexes support your full-text queries. MongoDB Vector Search indexes support similarity searches that compare query vectors to vector embeddings in your documents.
View the following guides to learn more about the MongoDB Search and MongoDB Vector Search features:
- MongoDB Search guide 
- MongoDB Vector Search guide 
MongoDB Search
To create MongoDB Search indexes, perform the following actions:
- Call the - create()method on the- Schemafacade in your migration file.
- Pass - create()the collection name and a callback method with a- MongoDB\Laravel\Schema\Blueprintparameter.
- Pass the MongoDB Search index creation details to the - searchIndex()method on the- Blueprintinstance.
This example migration creates the following MongoDB Search indexes on the
galaxies collection:
- dynamic_index: Creates dynamic mappings
- auto_index: Supports autocomplete queries on the- namefield
Click the VIEW OUTPUT button to see the MongoDB Search indexes created by running the migration:
Schema::create('galaxies', function (Blueprint $collection) {     $collection->searchIndex([         'mappings' => [             'dynamic' => true,         ],     ], 'dynamic_index');     $collection->searchIndex([         'mappings' => [             'fields' => [                 'name' => [                     ['type' => 'string', 'analyzer' => 'lucene.english'],                     ['type' => 'autocomplete', 'analyzer' => 'lucene.english'],                     ['type' => 'token'],                 ],             ],         ],     ], 'auto_index'); }); 
{   "id": "...",   "name": "dynamic_index",   "type": "search",   "status": "READY",   "queryable": true,   "latestDefinition": {     "mappings": { "dynamic": true }   },   ... } {   "id": "...",   "name": "auto_index",   "type": "search",   "status": "READY",   "queryable": true,   "latestDefinition": {     "mappings": {       "fields": { "name": [         { "type": "string", "analyzer": "lucene.english" },         { "type": "autocomplete", "analyzer": "lucene.english" },         { "type": "token" }       ] }     }   },   ... } 
MongoDB Vector Search
To create MongoDB Vector Search indexes, perform the following actions:
- Call the - create()method on the- Schemafacade in your migration file.
- Pass - create()the collection name and a callback method with a- MongoDB\Laravel\Schema\Blueprintparameter.
- Pass the vector index creation details to the - vectorSearchIndex()method on the- Blueprintinstance.
The following example migration creates a MongoDB Vector Search index called
vs_index on the galaxies collection.
Click the VIEW OUTPUT button to see the MongoDB Vector Search indexes created by running the migration:
Schema::create('galaxies', function (Blueprint $collection) {     $collection->vectorSearchIndex([         'fields' => [             [                 'type' => 'vector',                 'numDimensions' => 4,                 'path' => 'embeddings',                 'similarity' => 'cosine',             ],         ],     ], 'vs_index'); }); 
{   "id": "...",   "name": "vs_index",   "type": "vectorSearch",   "status": "READY",   "queryable": true,   "latestDefinition": {     "fields": [ {         "type": "vector",         "numDimensions": 4,         "path": "embeddings",         "similarity": "cosine"     } ]   },   ... } 
Drop a MongoDB Search or MongoDB Vector Search Index
To drop a MongoDB Search or MongoDB Vector Search index from a collection, perform the following actions:
- Call the - table()method on the- Schemafacade in your migration file.
- Pass it the collection name and a callback method with a - MongoDB\Laravel\Schema\Blueprintparameter.
- Call the - dropSearchIndex()method with the MongoDB Search or MongoDB Vector Search index name on the- Blueprintinstance.
The following example migration drops an index called auto_index
from the galaxies collection:
Schema::table('galaxies', function (Blueprint $collection) {     $collection->dropSearchIndex('auto_index'); });