Skip to main content

Overview

BaseModelMongo is the MongoDB equivalent of BaseModel, providing the same REST API capabilities for MongoDB collections using the Laravel MongoDB package.
This class requires the mongodb/laravel-mongodb package to be installed separately. It is not included by default.

Installation

To use MongoDB models, install the Laravel MongoDB package:
Configure your MongoDB connection in config/database.php:

Basic Usage

Create a MongoDB model by extending BaseModelMongo:

Constants

BaseModelMongo supports the same constants as BaseModel:
string
required
The model identifier used in API responses and logging
array
default:"[]"
Default columns to select when querying the model
array
default:"[]"
Whitelisted relations that can be eager loaded via the API
string|null
default:"null"
The field name for self-referencing hierarchy (e.g., ‘parent_id’)

MongoDB-Specific Relations

BaseModelMongo provides helper methods for MongoDB relations:

belongsToMongo

Define a MongoDB BelongsTo relationship:

hasManyMongo

Define a MongoDB HasMany relationship:

hasOneMongo

Define a MongoDB HasOne relationship:

Features

All BaseModel features work with BaseModelMongo:
  • Dynamic filtering with operators
  • Relation loading with field selection
  • Hierarchical data support
  • Role-based field restrictions
  • Validation and form requests
  • Export to Excel/PDF

Differences from BaseModel

  1. Connection: Uses MongoDB driver instead of SQL
  2. Collection: Uses $collection property instead of $table
  3. Relations: MongoDB-specific relation methods
  4. Schema: Schemaless - no migrations required
  5. Query Builder: MongoDB query builder syntax

Example Service

Use BaseModelMongo with BaseService just like regular models:

Example Controller

Controllers work identically with MongoDB models:

Limitations

Some SQL-specific features may not work with MongoDB:
  • Complex joins across different databases
  • SQL-specific operators (some may need MongoDB equivalents)
  • Database transactions work differently in MongoDB

Next Steps

BaseModel

Learn about the SQL version

BaseService

Using services with MongoDB models

Filtering

Dynamic filtering with MongoDB

Relations

Working with MongoDB relations