Docs Menu
Docs Home
/ / /
Laravel MongoDB
/

Schema Builder

On this page

  • Overview
  • Perform Laravel Migrations
  • Create a Migration Class
  • Run or Roll Back a Migration
  • Check Whether a Collection Exists
  • Manage Indexes
  • Create an Index
  • Specify Index Options
  • Create Sparse, TTL, and Unique Indexes
  • Create a Geospatial Index
  • Drop an Index

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.

Laravel MongoDB 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 Laravel MongoDB and show examples of how to use them:

Note

Laravel MongoDB 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.

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.

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 with MongoDB\Laravel\Schema\Blueprint if it is referenced in your migration

  • Use only commands and syntax supported by Laravel MongoDB

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 valid mongodb entry in your config/database.php file

  • Specify "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 migration

  • down(), which drops the collection and all the indexes on it when you roll back the migration

<?php
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');
}
};

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.

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');
}

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.

To create indexes, call the create() method on the Schema 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 and launch_date, specifying a descending sort order on launch_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']);
});

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 ],
],
);
});

To learn more about index options, see Options for All Index Types in the Server manual.

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, call the create() method on the Schema facade in your migration file. Pass create() the collection name and a callback method with a MongoDB\Laravel\Schema\Blueprint parameter. Call the appropriate helper method 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);
});

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]);
});

To learn more about these indexes, see Index Properties in the Server manual.

In MongoDB, geospatial indexes let you query geospatial coordinate data for inclusion, intersection, and proximity.

To create geospatial indexes, call the create() method on the Schema facade in your migration file. Pass create() the collection name and a callback method with a MongoDB\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');
});

To learn more about geospatial indexes, see Geospatial Indexes in the Server manual.

To drop indexes from a collection, call the table() method on the Schema 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 the Blueprint 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');
});
← Relationships