Skip to content

Support adding schema validation #3397

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/Schema/Blueprint.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use MongoDB\Laravel\Connection;

use function array_flip;
use function array_merge;
use function implode;
use function in_array;
use function is_array;
Expand Down Expand Up @@ -117,6 +118,24 @@ public function hasIndex($indexOrColumns = null)
return false;
}

public function jsonSchema(
array $schema = [],
?string $validationLevel = null,
?string $validationAction = null,
): void {
$options = array_merge(
[
'validator' => [
'$jsonSchema' => $schema,
],
],
$validationLevel ? ['validationLevel' => $validationLevel] : [],
$validationAction ? ['validationAction' => $validationAction] : [],
);

$this->connection->getDatabase()->modifyCollection($this->collection->getCollectionName(), $options);
}

/**
* @param string|array $indexOrColumns
*
Expand Down
33 changes: 33 additions & 0 deletions tests/SchemaTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,39 @@ public function testCreateWithOptions(): void
$this->assertEquals(1024, $collection['options']['size']);
}

public function testCreateWithSchemaValidator(): void
{
$schema = [
'bsonType' => 'object',
'required' => [ 'username' ],
'properties' => [
'username' => [
'bsonType' => 'string',
'description' => 'must be a string and is required',
],
],
];

Schema::create(self::COLL_2, function (Blueprint $collection) use ($schema) {
$collection->string('username');
$collection->jsonSchema(schema: $schema, validationAction: 'warn');
});

$this->assertTrue(Schema::hasCollection(self::COLL_2));
$this->assertTrue(Schema::hasTable(self::COLL_2));

$collection = Schema::getCollection(self::COLL_2);
$this->assertEquals(
['$jsonSchema' => $schema],
$collection['options']['validator'],
);

$this->assertEquals(
'warn',
$collection['options']['validationAction'],
);
}

public function testDrop(): void
{
Schema::create(self::COLL_1);
Expand Down
Loading