Laravel MongoDB
repository·5.x·Indexed 27 days ago
https://github.com/mongodb/laravel-mongodbProvides MongoDB support for Laravel applications by extending Eloquent models and the Query builder. It allows developers to use standard Laravel database APIs with a MongoDB backend, including support for MongoDB as a cache and session driver, BSON type handling via specialized Eloquent models, and integration with the ext-mongodb PHP extension.
What's inside laravel-mongodb
- Laravel MongoDB extends the Eloquent model and Query builder to support MongoDB. It is designed to be a drop-in replacement for standard Laravel database interactions by extending original Laravel classes, meaning it uses the exact same methods and API as the standard Laravel database layer.
Improve Novelty in Skills
5.xLow novelty means the content mostly restates information the model already knows from training data. A score below 3 is a warning sign that the skill may not justify its context window cost.
Common low-novelty patterns:
- Restating official documentation.
- Describing standard patterns or common best practices.
- Covering well-documented public APIs without proprietary context.
Advice to fix:
- Focus on proprietary or non-obvious information: internal API conventions, organization-specific workflows, undocumented gotchas, non-standard configurations, or domain knowledge.
- Cut or heavily compress sections that restate public knowledge.
Configure prerequisites for LLM scoring
5.xLLM scoring in
skill-validatoruses theclaude-cliprovider. This provider relies on a localclaudebinary and uses your existing CLI authentication rather than API keys.To use LLM scoring, you must:
- Install the Claude Code CLI (verify with
claude --version). On macOS, use:curl -fsSL https://claude.ai/install.sh | bash. - Ensure you have an authenticated session by running
claudeinteractively and completing the login process.
# Install Claude Code CLI on macOS curl -fsSL https://claude.ai/install.sh | bash # Verify installation claude --version- Install the Claude Code CLI (verify with
Define a MongoDB Eloquent Model
5.xTo use MongoDB with Eloquent, your models must extend
MongoDB\Laravel\Eloquent\Modelor use theDocumentModeltrait. Useprotected $tableto define the collection name (note thatprotected $collectionis no longer used). Ensure you cast foreign keys tostringin the$castsarray to prevent BSON type mismatches during queries.<?php namespace App\Models; use MongoDB\Laravel\Eloquent\Model; final class Post extends Model { protected $connection = 'mongodb'; protected $table = 'posts'; // Use $table, not $collection protected $fillable = ['title', 'body', 'author_id', 'published_at']; protected $casts = [ 'author_id' => 'string', // Cast FK to string for relationship matching 'published_at' => 'datetime', ]; }Perform manual content review for Agent Skills
5.xWhen reviewing the content of a
SKILL.mdfile, evaluate it against the following criteria to ensure high quality:- Examples: Does the skill provide examples of expected inputs and outputs?
- Edge cases: Does the skill document common edge cases or failure modes?
- Scope-gating: Does the skill define when to stop/continue, prerequisites, and conditions for branching paths?
- MongoDB data access: If the skill requires MongoDB contextual data, does it instruct agents to use the MCP server for auth and tool calls? (Skip if not applicable).
Failing these checks provides non-blocking areas for Subject Matter Experts (SMEs) to address before publishing.
Use Auto-embedding for Vector Search
5.xAtlas Auto-embedding is the recommended approach for text fields. Atlas automatically generates and maintains embeddings on insert and update, meaning no PHP code is required to handle vector generation or storage.
To use this approach:
- Create a migration using
vectorSearchIndexwith theautoEmbedtype. - Insert documents normally by providing the source text field.
- Query using the
queryTextparameter in an aggregation pipeline, which allows Atlas to auto-embed the search string.
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Support\Facades\Schema; return new class extends Migration { public function up(): void { Schema::connection('mongodb')->table('products', function ($collection): void { $collection->vectorSearchIndex([ 'fields' => [ [ 'type' => 'autoEmbed', 'modality' => 'text', 'path' => 'description', // source text field 'model' => 'voyage-4', ], ['type' => 'filter', 'path' => 'category'], ], ], 'products_vector'); }); } };- Create a migration using
Improve Actionability in Skills
5.xLow actionability means an agent cannot follow instructions step-by-step. Common causes include abstract advice, missing intermediate steps, assumptions about unprovided context, or a lack of input/output examples.
Advice to fix:
- Convert abstract guidance into numbered steps.
- Add examples.
- Fill in any gaps where an agent would need to guess the next action.
Configure the MongoDB connection in Laravel
5.xTo use MongoDB, add a
mongodbconnection entry to yourconfig/database.phpfile and define the connection details in your.envfile.- Update
config/database.phpwith themongodbdriver configuration. - Set
MONGODB_URIandMONGODB_DATABASEin your.envfile.
// config/database.php 'connections' => [ 'mongodb' => [ 'driver' => 'mongodb', 'dsn' => env('MONGODB_URI', 'mongodb://localhost:27017'), 'database' => env('MONGODB_DATABASE', 'laravel'), ], ],# .env MONGODB_URI=mongodb://localhost:27017 MONGODB_DATABASE=laravel- Update
Configure cross-database relationships (MongoDB ↔ SQL)
5.xTo relate a SQL database (e.g., MySQL) to a MongoDB database, follow these rules:
- Apply
HybridRelationsonly to the SQL model. Never add this trait to the MongoDB model. - Store MongoDB IDs in SQL: The SQL table must store the MongoDB
_idas a string column (e.g.,VARCHAR(24)). - Cast Foreign Keys in MongoDB: In the MongoDB model, cast the foreign key to a
stringto facilitate direct queries.
SQL Model Setup: Use the
MongoDB\Laravel\Eloquent\HybridRelationstrait.MongoDB Model Setup: Cast the reference field to
stringand use standard relation methods.// SQL model (e.g. User in MySQL) use MongoDB\Laravel\Eloquent\HybridRelations; final class User extends \Illuminate\Database\Eloquent\Model { use HybridRelations; // ONLY on the SQL model public function posts(): \MongoDB\Laravel\Relations\HasMany { return $this->hasMany(\App\Models\Post::class, 'user_id'); } } // MongoDB model (e.g. Post) final class Post extends \MongoDB\Laravel\Eloquent\Model { protected $casts = ['user_id' => 'string']; public function user(): \MongoDB\Laravel\Relations\BelongsTo { return $this->belongsTo(User::class, 'user_id'); } }- Apply
Replace `withCount`, `withAvg`, and `withSum` with aggregations
5.xThe methods
withCount(),withAvg(), andwithSum()are not supported on MongoDB models. To achieve these results, use theraw()method to execute an aggregation pipeline involving$lookupand$size,$avg, or$sum.// CORRECT $posts = Post::raw(fn ($c) => $c->aggregate([ ['$lookup' => [ 'from' => 'comments', 'localField' => '_id', 'foreignField' => 'post_id', 'as' => 'comments', ]], ['$addFields' => ['comments_count' => ['$size' => '$comments']]], ['$project' => ['comments' => 0]], ]));Interpret Review Report Scores
5.xReview reports use a scale of 1-5 for each dimension. The overall score is the mean of all dimensions. Use the following scale to interpret results:
Score Meaning 5 Excellent — genuinely outstanding on this dimension 4 Good — minor improvements possible but solid 3 Adequate — functional but has clear room for improvement 2 Needs work — notable issues that should be addressed 1 Poor — fundamental problems on this dimension Improve Token Efficiency in Skills
5.xLow token efficiency means content is bloated relative to its instructional value. Common causes include redundant explanations, non-helpful boilerplate, verbose phrasing, or unnecessary content.
Advice to fix:
- Cut redundant sections.
- Replace verbose explanations with concise directives.
- Remove boilerplate text. Ensure every sentence provides necessary information.