Schema Builder
On this page
Overview
Laravel provides a facade to access the schema builder class Schema
,
which lets you create and modify tables. 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:
Note
The Laravel Integration supports managing indexes and collections, but excludes support for MongoDB JSON schemas for data validation. To learn more about JSON schema validation, see Schema Validation in the Server manual.
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\Blueprint
import withMongoDB\Laravel\Schema\Blueprint
if it is referenced in your migrationUse 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
connections
array item contains a validmongodb
entry in yourconfig/database.php
fileSpecify
"mongodb"
in the$connection
field 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 migrationdown()
, 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.
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 theSchema
facade in your migration file.Pass it the collection name and a callback method with a
MongoDB\Laravel\Schema\Blueprint
parameter.Specify the index creation details on the
Blueprint
instance.
The following example migration creates indexes on the following collection fields:
Single field index on
mission_type
Compound index on
launch_location
andlaunch_date
, specifying a descending sort order onlaunch_date
Unique index on the
mission_id
field, 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 theSchema
facade in your migration file.Pass
create()
the collection name and a callback method with aMongoDB\Laravel\Schema\Blueprint
parameter.Call the appropriate helper method for the index type on the
Blueprint
instance 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 theSchema
facade in your migration file.Pass
create()
the collection name and a callback method with aMongoDB\Laravel\Schema\Blueprint
parameter.Specify the geospatial index creation details on the
Blueprint
instance.
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 theSchema
facade in your migration file.Pass it the table name and a callback method with a
MongoDB\Laravel\Schema\Blueprint
parameter.Call the
dropIndex()
method with the index name on theBlueprint
instance.
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 Atlas Search and Vector Search Indexes
In MongoDB, Atlas Search indexes support your full-text queries. Atlas 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 Atlas Search and Vector Search features:
Atlas Search guide
Atlas Vector Search guide
Atlas Search
To create Atlas Search indexes, perform the following actions:
Call the
create()
method on theSchema
facade in your migration file.Pass
create()
the collection name and a callback method with aMongoDB\Laravel\Schema\Blueprint
parameter.Pass the Atlas index creation details to the
searchIndex()
method on theBlueprint
instance.
This example migration creates the following Atlas Search indexes on the
galaxies
collection:
dynamic_index
: Creates dynamic mappingsauto_index
: Supports autocomplete queries on thename
field
Click the VIEW OUTPUT button to see the 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" } ] } } }, ... }
Vector Search
To create Vector Search indexes, perform the following actions:
Call the
create()
method on theSchema
facade in your migration file.Pass
create()
the collection name and a callback method with aMongoDB\Laravel\Schema\Blueprint
parameter.Pass the vector index creation details to the
vectorSearchIndex()
method on theBlueprint
instance.
The following example migration creates a Vector Search index called
vs_index
on the galaxies
collection.
Click the VIEW OUTPUT button to see the 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 Search Index
To drop an Atlas Search or Vector Search index from a collection, perform the following actions:
Call the
table()
method on theSchema
facade in your migration file.Pass it the collection name and a callback method with a
MongoDB\Laravel\Schema\Blueprint
parameter.Call the
dropSearchIndex()
method with the Search index name on theBlueprint
instance.
The following example migration drops an index called auto_index
from the galaxies
collection:
Schema::table('galaxies', function (Blueprint $collection) { $collection->dropSearchIndex('auto_index'); });