Laravel MongoDB

repository·5.x·Indexed 27 days ago

https://github.com/mongodb/laravel-mongodb

Provides 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.

Tokens
18.6K
Snippets
58
Records
94
Agent score
91%

What's inside laravel-mongodb

  1. Overview of Laravel MongoDB

    5.x
    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.
  2. Improve Novelty in Skills

    5.x

    Low 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.
  3. Configure prerequisites for LLM scoring

    5.x

    LLM scoring in skill-validator uses the claude-cli provider. This provider relies on a local claude binary and uses your existing CLI authentication rather than API keys.

    To use LLM scoring, you must:

    1. Install the Claude Code CLI (verify with claude --version). On macOS, use: curl -fsSL https://claude.ai/install.sh | bash.
    2. Ensure you have an authenticated session by running claude interactively and completing the login process.
    # Install Claude Code CLI on macOS
    curl -fsSL https://claude.ai/install.sh | bash
    
    # Verify installation
    claude --version
  4. Define a MongoDB Eloquent Model

    5.x

    To use MongoDB with Eloquent, your models must extend MongoDB\Laravel\Eloquent\Model or use the DocumentModel trait. Use protected $table to define the collection name (note that protected $collection is no longer used). Ensure you cast foreign keys to string in the $casts array 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',
        ];
    }
  5. Perform manual content review for Agent Skills

    5.x

    When reviewing the content of a SKILL.md file, 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.

  6. Use Auto-embedding for Vector Search

    5.x

    Atlas 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:

    1. Create a migration using vectorSearchIndex with the autoEmbed type.
    2. Insert documents normally by providing the source text field.
    3. Query using the queryText parameter 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');
            });
        }
    };
  7. Improve Actionability in Skills

    5.x

    Low 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.
  8. Configure the MongoDB connection in Laravel

    5.x

    To use MongoDB, add a mongodb connection entry to your config/database.php file and define the connection details in your .env file.

    1. Update config/database.php with the mongodb driver configuration.
    2. Set MONGODB_URI and MONGODB_DATABASE in your .env file.
    // 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
  9. Configure cross-database relationships (MongoDB ↔ SQL)

    5.x

    To relate a SQL database (e.g., MySQL) to a MongoDB database, follow these rules:

    1. Apply HybridRelations only to the SQL model. Never add this trait to the MongoDB model.
    2. Store MongoDB IDs in SQL: The SQL table must store the MongoDB _id as a string column (e.g., VARCHAR(24)).
    3. Cast Foreign Keys in MongoDB: In the MongoDB model, cast the foreign key to a string to facilitate direct queries.

    SQL Model Setup: Use the MongoDB\Laravel\Eloquent\HybridRelations trait.

    MongoDB Model Setup: Cast the reference field to string and 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');
        }
    }
  10. Replace `withCount`, `withAvg`, and `withSum` with aggregations

    5.x

    The methods withCount(), withAvg(), and withSum() are not supported on MongoDB models. To achieve these results, use the raw() method to execute an aggregation pipeline involving $lookup and $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]],
    ]));
  11. Interpret Review Report Scores

    5.x

    Review 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:

    ScoreMeaning
    5Excellent — genuinely outstanding on this dimension
    4Good — minor improvements possible but solid
    3Adequate — functional but has clear room for improvement
    2Needs work — notable issues that should be addressed
    1Poor — fundamental problems on this dimension
  12. Improve Token Efficiency in Skills

    5.x

    Low 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.