Download the PHP package ciayo/moloquent without Composer
On this page you can find all versions of the php package ciayo/moloquent. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package moloquent
Laravel MongoDB
An Eloquent model and Query builder with support for MongoDB, using the original Laravel API. This library extends the original Laravel classes, so it uses exactly the same methods.
Table of contents
- Installation
- Upgrading
- Configuration
- Eloquent
- Optional: Alias
- Query Builder
- Schema
- Extensions
- Troubleshooting
- Examples
Installation
Make sure you have the MongoDB PHP driver installed. You can find installation instructions at http://php.net/manual/en/mongodb.installation.php
WARNING: The old mongo PHP driver is not supported anymore in versions >= 3.0.
Installation using composer:
Laravel version Compatibility
Laravel | Package |
---|---|
4.2.x | 2.0.x |
5.0.x | 2.1.x |
5.1.x | 2.2.x or 3.0.x |
5.2.x | 2.3.x or 3.0.x |
5.3.x | 3.1.x or 3.2.x |
5.4.x | 3.2.x |
And add the service provider in config/app.php
:
For usage with Lumen, add the service provider in bootstrap/app.php
. In this file, you will also need to enable Eloquent. You must however ensure that your call to $app->withEloquent();
is below where you have registered the MongodbServiceProvider
:
The service provider will register a mongodb database extension with the original database manager. There is no need to register additional facades or objects. When using mongodb connections, Laravel will automatically provide you with the corresponding mongodb objects.
For usage outside Laravel, check out the Capsule manager and add:
Upgrading
Upgrading from version 2 to 3
In this new major release which supports the new mongodb PHP extension, we also moved the location of the Model class and replaced the MySQL model class with a trait.
Please change all Jenssegers\Mongodb\Model
references to Jenssegers\Mongodb\Eloquent\Model
either at the top of your model files, or your registered alias.
If you are using hybrid relations, your MySQL classes should now extend the original Eloquent model class Illuminate\Database\Eloquent\Model
instead of the removed Jenssegers\Eloquent\Model
. Instead use the new Jenssegers\Mongodb\Eloquent\HybridRelations
trait. This should make things more clear as there is only one single model class in this package.
Embedded relations now return an Illuminate\Database\Eloquent\Collection
rather than a custom Collection class. If you were using one of the special methods that were available, convert them to Collection operations.
Configuration
Change your default database connection name in config/database.php
:
And add a new mongodb connection:
You can connect to multiple servers or replica sets with the following configuration:
Alternatively, you can use MongoDB connection string:
Please refer to MongoDB official docs for its URI format: https://docs.mongodb.com/manual/reference/connection-string/
Eloquent
This package includes a MongoDB enabled Eloquent class that you can use to define models for corresponding collections.
Note that we did not tell Eloquent which collection to use for the User
model. Just like the original Eloquent, the lower-case, plural name of the class will be used as the collection name unless another name is explicitly specified. You may specify a custom collection (alias for table) by defining a collection
property on your model:
NOTE: Eloquent will also assume that each collection has a primary key column named id. You may define a primaryKey
property to override this convention. Likewise, you may define a connection
property to override the name of the database connection that should be used when utilizing the model.
Everything else (should) work just like the original Eloquent model. Read more about the Eloquent on http://laravel.com/docs/eloquent
Optional: Alias
You may also register an alias for the MongoDB model by adding the following to the alias array in config/app.php
:
This will allow you to use the registered alias like:
Query Builder
The database driver plugs right into the original query builder. When using mongodb connections, you will be able to build fluent queries to perform database operations. For your convenience, there is a collection
alias for table
as well as some additional mongodb specific operators/operations.
If you did not change your default database connection, you will need to specify it when querying.
Read more about the query builder on http://laravel.com/docs/queries
Schema
The database driver also has (limited) schema builder support. You can easily manipulate collections and set indexes:
Supported operations are:
- create and drop
- collection
- hasCollection
- index and dropIndex (compound indexes supported as well)
- unique
- background, sparse, expire, geospatial (MongoDB specific)
All other (unsupported) operations are implemented as dummy pass-through methods, because MongoDB does not use a predefined schema. Read more about the schema builder on http://laravel.com/docs/schema
Geospatial indexes
Geospatial indexes are handy for querying location-based documents. They come in two forms: 2d
and 2dsphere
. Use the schema builder to add these to a collection.
To add a 2d
index:
To add a 2dsphere
index:
Extensions
Auth
If you want to use Laravel's native Auth functionality, register this included service provider:
This service provider will slightly modify the internal DatabaseReminderRepository to add support for MongoDB based password reminders. If you don't use password reminders, you don't have to register this service provider and everything else should work just fine.
Queues
If you want to use MongoDB as your database backend, change the the driver in config/queue.php
:
If you want to use MongoDB to handle failed jobs, change the database in config/queue.php
:
And add the service provider in config/app.php
:
Sentry
If you want to use this library with Sentry, then check out https://github.com/jenssegers/Laravel-MongoDB-Sentry
Sessions
The MongoDB session driver is available in a separate package, check out https://github.com/jenssegers/Laravel-MongoDB-Session
Examples
Basic Usage
Retrieving All Models
Retrieving A Record By Primary Key
Wheres
Or Statements
And Statements
Using Where In With An Array
When using whereNotIn
objects will be returned if the field is non existent. Combine with whereNotNull('age')
to leave out those documents.
Using Where Between
Where null
Order By
Offset & Limit
Distinct
Distinct requires a field for which to return the distinct values.
Distinct can be combined with where:
Advanced Wheres
Group By
Selected columns that are not grouped will be aggregated with the $last function.
Aggregation
Aggregations are only available for MongoDB versions greater than 2.2.
Aggregations can be combined with where:
Aggregations can be also used on subdocuments:
NOTE: this aggreagtion only works with single subdocuments (like embedsOne) not subdocument arrays (like embedsMany)
Like
Incrementing or decrementing a value of a column
Perform increments or decrements (default 1) on specified attributes:
The number of updated objects is returned:
You may also specify additional columns to update:
Soft deleting
When soft deleting a model, it is not actually removed from your database. Instead, a deleted_at timestamp is set on the record. To enable soft deletes for a model, apply the SoftDeletingTrait to the model:
For more information check http://laravel.com/docs/eloquent#soft-deleting
MongoDB specific operators
Exists
Matches documents that have the specified field.
All
Matches arrays that contain all elements specified in the query.
Size
Selects documents if the array field is a specified size.
Regex
Selects documents where values match a specified regular expression.
NOTE: you can also use the Laravel regexp operations. These are a bit more flexible and will automatically convert your regular expression string to a MongoDB\BSON\Regex object.
And the inverse:
Type
Selects documents if a field is of the specified type. For more information check: http://docs.mongodb.org/manual/reference/operator/query/type/#op._S_type
Mod
Performs a modulo operation on the value of a field and selects documents with a specified result.
Near
NOTE: Specify coordinates in this order: longitude, latitude
.
GeoWithin
GeoIntersects
Where
Matches documents that satisfy a JavaScript expression. For more information check http://docs.mongodb.org/manual/reference/operator/query/where/#op._S_where
Inserts, updates and deletes
Inserting, updating and deleting records works just like the original Eloquent.
Saving a new model
You may also use the create method to save a new model in a single line:
Updating a model
To update a model, you may retrieve it, change an attribute, and use the save method.
There is also support for upsert operations, check https://github.com/jenssegers/laravel-mongodb#mongodb-specific-operations
Deleting a model
To delete a model, simply call the delete method on the instance:
Or deleting a model by its key:
For more information about model manipulation, check http://laravel.com/docs/eloquent#insert-update-delete
Dates
Eloquent allows you to work with Carbon/DateTime objects instead of MongoDate objects. Internally, these dates will be converted to MongoDate objects when saved to the database. If you wish to use this functionality on non-default date fields you will need to manually specify them as described here: http://laravel.com/docs/eloquent#date-mutators
Example:
Which allows you to execute queries like:
Relations
Supported relations are:
- hasOne
- hasMany
- belongsTo
- belongsToMany
- embedsOne
- embedsMany
Example:
And the inverse relation:
The belongsToMany relation will not use a pivot "table", but will push id's to a __related_ids__ attribute instead. This makes the second parameter for the belongsToMany method useless. If you want to define custom keys for your relation, set it to null
:
Other relations are not yet supported, but may be added in the future. Read more about these relations on http://laravel.com/docs/eloquent#relationships
EmbedsMany Relations
If you want to embed models, rather than referencing them, you can use the embedsMany
relation. This relation is similar to the hasMany
relation, but embeds the models inside the parent object.
REMEMBER: these relations return Eloquent collections, they don't return query builder objects!
You access the embedded models through the dynamic property:
The inverse relation is automagically available, you don't need to define this reverse relation.
Inserting and updating embedded models works similar to the hasMany
relation:
You can update embedded models using their save
method (available since release 2.0.0):
You can remove an embedded model by using the destroy
method on the relation, or the delete
method on the model (available since release 2.0.0):
If you want to add or remove an embedded model, without touching the database, you can use the associate
and dissociate
methods. To eventually write the changes to the database, save the parent object:
Like other relations, embedsMany assumes the local key of the relationship based on the model name. You can override the default local key by passing a second argument to the embedsMany method:
Embedded relations will return a Collection of embedded items instead of a query builder. Check out the available operations here: https://laravel.com/docs/master/collections
EmbedsOne Relations
The embedsOne relation is similar to the EmbedsMany relation, but only embeds a single model.
You access the embedded models through the dynamic property:
Inserting and updating embedded models works similar to the hasOne
relation:
You can update the embedded model using the save
method (available since release 2.0.0):
You can replace the embedded model with a new model like this:
MySQL Relations
If you're using a hybrid MongoDB and SQL setup, you're in luck! The model will automatically return a MongoDB- or SQL-relation based on the type of the related model. Of course, if you want this functionality to work both ways, your SQL-models will need use the Jenssegers\Mongodb\Eloquent\HybridRelations
trait. Note that this functionality only works for hasOne, hasMany and belongsTo relations.
Example SQL-based User model:
And the Mongodb-based Message model:
Raw Expressions
These expressions will be injected directly into the query.
You can also perform raw expressions on the internal MongoCollection object. If this is executed on the model class, it will return a collection of models. If this is executed on the query builder, it will return the original response.
Optional: if you don't pass a closure to the raw method, the internal MongoCollection object will be accessible:
The internal MongoClient and MongoDB objects can be accessed like this:
MongoDB specific operations
Cursor timeout
To prevent MongoCursorTimeout exceptions, you can manually set a timeout value that will be applied to the cursor:
Upsert
Update or insert a document. Additional options for the update method are passed directly to the native update method.
Projections
You can apply projections to your queries using the project
method.
Projections with Pagination
Push
Add an items to an array.
If you don't want duplicate items, set the third parameter to true
:
Pull
Remove an item from an array.
Unset
Remove one or more fields from a document.
You can also perform an unset on a model.
Query Caching
You may easily cache the results of a query using the remember method:
From: http://laravel.com/docs/queries#caching-queries
Query Logging
By default, Laravel keeps a log in memory of all queries that have been run for the current request. However, in some cases, such as when inserting a large number of rows, this can cause the application to use excess memory. To disable the log, you may use the disableQueryLog
method:
All versions of moloquent with dependencies
illuminate/container Version ^5.5
illuminate/database Version ^5.5
illuminate/events Version ^5.5
mongodb/mongodb Version ^1.0.0