Giter Club home page Giter Club logo

mongolid-laravel's Introduction

Build Status Coverage Status Latest Stable Version Monthly Downloads Latest Unstable Version License

MongoLid

MongoLid (Laravel Package)

Introduction

MongoLid ODM (Object Document Mapper) provides a beautiful, simple implementation for working with MongoDB. Each database collection can have a corresponding "Model" which is used to interact with that collection.

Note: The ODM implementation is within the (non laravel) mongolid repository.

Installation

Install with composer require (use one of the above tags if needed).

composer require leroy-merlin-br/mongolid-laravel

Note: Mongolid Laravel 2.0 only supports Laravel 5.4+. For older versions use the tags:

  • Laravel 4.2 "leroy-merlin-br/mongolid-laravel": "^0.7"
  • Laravel 5.1 "leroy-merlin-br/mongolid-laravel": "2.0.0-beta4"
  • Laravel 5.2 "leroy-merlin-br/mongolid-laravel": "2.0.0-beta6"
  • Laravel 5.3 "leroy-merlin-br/mongolid-laravel": "2.0.0-beta6"

Make sure to set minimum stability to dev when using a beta tag (composer config minimum-stability dev).

Note: If you are using Laravel 5.5, the next steps for providers and aliases are unnecessaries. MongoLid supports Laravel new Package Discovery.

In your config/app.php add 'MongolidLaravel\MongolidServiceProvider' to the end of the $providers array

'providers' => [
    Illuminate\Translation\TranslationServiceProvider::class,
    Illuminate\Validation\ValidationServiceProvider::class,
    Illuminate\View\ViewServiceProvider::class,
    ...
    MongolidLaravel\MongolidServiceProvider::class,
],

(Optional) At the end of config/app.php add 'MongoLid' => 'MongolidLaravel\MongoLidModel' to the $aliases array

'aliases' => [
    'App'         => Illuminate\Support\Facades\App::class,
    'Artisan'     => Illuminate\Support\Facades\Artisan::class,
    ...
    'MongoLid'    => MongolidLaravel\MongoLidModel::class,
],

Lastly, be sure to configure a database connection in config/database.php:

Paste the settings bellow at the end of your config/database.php, before the last ];:

Notice: It must be outside of connections array.

/*
|--------------------------------------------------------------------------
| MongoDB Databases
|--------------------------------------------------------------------------
|
| MongoDB is a document database with the scalability and flexibility
| that you want with the querying and indexing that you need.
| Mongolid Laravel use this config to starting querying right now.
|
*/

'mongodb' => [
    'default' => [
        'host'     => env('DB_HOST', '127.0.0.1'),
        'port'     => env('DB_PORT_NUMBER', 27017),
        'database' => env('DB_DATABASE', 'my_database'),
        'username' => env('DB_USERNAME', null),
        'password' => env('DB_PASSWORD', null),
    ],
],

For cluster with automatic failover, you need to set cluster key containing all nodes along with replica_set name.

'mongodb' => [
    'default' => [
        'cluster' => [
            'replica_set' => env('DB_REPLICA_SET', null),
            'nodes' => [
                'primary' => [
                    'host' => env('DB_HOST_A', 'host-a'),
                    'port' => env('DB_PORT_A', 27017),
                ],
                'secondary' => [
                    'host' => env('DB_HOST_B', 'host-b'),
                    'port' => env('DB_PORT_B', 27017),
                ],
            ],
        ],
        'database' => env('DB_DATABASE', 'mongolid'),
        'username' => env('DB_USERNAME', null),
        'password' => env('DB_PASSWORD', null),
    ],
],

You can configure as much nodes as needed, node names (e.g. primary and secondary ) are optional.

Note: If you don't specify the mongodb key in your config/database.php MongoLid will automatically try to connect to '127.0.0.1:27017' and use a database named 'mongolid'.

You may optionally provide a connection_string key to set a fully-assembled connection string that will override all other connection options. More info about connection string are found in MongoDB documentation.

'mongodb' => [
    'default' => [
        'connection_string' => 'mongodb://host-a:27017,host-b:27917/mongolid?replicaSet=rs-ds123',
    ],
],

Also, it is possible to pass options and driver_options to MongoDB Client. Mongolid always overrides typeMap configuration of driver_options to array because it makes easier to use internally with models. Possible options and driver_options are present on MongoDB\Client documentation.

Basic Usage

To get started, create an MongoLid model. Models typically live in the app/models directory, but you are free to place them anywhere that can be auto-loaded according to your composer.json file.

Defining a MongoLid Model

<?php
namespace App;

use MongolidLaravel\MongolidModel;

class User extends MongolidModel
{

}

In a nutshell, that's it!

For further reading about models, CRUD operations, relationships and more, check the Read the Docs: leroy-merlin-br.github.com/mongolid.

Mongolid Docs

Authentication

MongoLid Laravel comes with a Laravel auth provider. In order to use it, simply change the 'driver' provider value in your config/auth.php to mongolid and make sure that the class specified in model is a MongoLid model that implements the Authenticatable contract:

    'providers' => [

        // ...

        'users' => [
            'driver' => 'mongolid',
            'model' => \App\User::class
        ],

        // ...

    ],

The User model should implement the Authenticatable interface:

<?php
namespace App;

use Illuminate\Contracts\Auth\Authenticatable;
use MongolidLaravel\MongolidModel;

class User extends MongolidModel implements Authenticatable
{
    /**
     * The database collection used by the model.
     *
     * @var string
     */
    protected $collection = 'users';

    /**
     * Get the name of the unique identifier for the user.
     *
     * @return string
     */
    public function getAuthIdentifierName()
    {
        return '_id';
    }

    /**
     * Get the unique identifier for the user.
     *
     * @return mixed
     */
    public function getAuthIdentifier()
    {
        return $this->_id;
    }

    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword()
    {
        return $this->password;
    }

    /**
     * Get the token value for the "remember me" session.
     *
     * @return string
     */
    public function getRememberToken()
    {
        return $this->remember_token;
    }


    /**
     * Set the token value for the "remember me" session.
     *
     * @param  string  $value
     */
    public function setRememberToken($value)
    {
        $this->remember_token = $value;
    }

    /**
     * Get the column name for the "remember me" token.
     *
     * @return string
     */
    public function getRememberTokenName()
    {
        return 'remember_token';
    }
}

Now, to log a user into your application, you may use the auth()->attempt() method. You can use any method regarding authentication.

Queue Failed Job Provider

Mongolid Laravel replaces Laravel queue failed job provider to use a collection instead of a table. To configure the provider, update failed key on queue.php to include collection name:

    'failed' => [
        'database' => 'mongodb',
        'collection' => 'failed_jobs',
    ],

Note: database key is irrelevant.

Troubleshooting

"PHP Fatal error: Class 'MongoDB\Client' not found in ..."

The MongoDB\Client class is contained in the MongoDB PHP Library and it requires MongoDB driver for PHP. Here is an installation guide for this driver. The driver is a PHP extension written in C and maintained by MongoDB. MongoLid and most other MongoDB PHP libraries utilize it in order to be fast and reliable.

"Class 'MongoDB\Client' not found in ..." in CLI persists even with MongoDB driver installed.

Make sure that the php.ini file used in the CLI environment includes the MongoDB extension. In some systems, the default PHP installation uses different .ini files for the web and CLI environments.

Run php --ini in a terminal to check the .ini that is being used.

To check if PHP in the CLI environment is importing the driver properly run php -i | grep mongo in your terminal. You should get output similar to:

$ php -i | grep mongo
mongodb
mongodb support => enabled
...

"This package requires php >=7.0 but your PHP version (X.X.X) does not satisfy that requirement."

The new (and improved) version 2.0 of Mongolid Laravel requires php7. If you are looking for the old PHP 5.x version, or other Laravel versions, head to the v0.8 branch.

License

MongoLid & MongoLid Laravel are free software distributed under the terms of the MIT license. Some of the code is based on the work of Taylor Otwell and contributors on laravel/framework, another free software distributed under the terms of the MIT license.

Additional information

Mongolid was proudly built by the Leroy Merlin Brazil team. See all the contributors.

Any questions, feel free to contact us.

Any issues, please report here.

mongolid-laravel's People

Contributors

andydune avatar carusogabriel avatar ckd avatar diegofelix avatar djonasm avatar edukazan avatar ezandonai avatar gabrielgomes94 avatar getuliomeirelles avatar gmsantos avatar guilhermeguitte avatar henrique221 avatar hfisaquiel avatar jmikola avatar orlandocavassani avatar outrunthewolf avatar ravanscafi avatar rplansky avatar saran87 avatar vagnerlg avatar vitorbari avatar williancs avatar zizaco avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mongolid-laravel's Issues

Regexp query not working

I have a snippet like this:

public function postSearch()
    {
        $company = new Company;     
        $result = $company->where(['name' => [ '$regex' => '/.*'.Input::get('search').'.*/i' ]]);
        $companydata = $result->toArray();      
        return Response::json([200, "OK", 'found' => $companydata]);
    }

And it doesn't work. It returns an empty array.

On the other hand, this works in MongoDB terminal:

> db.companies.find({name:{$regex: /.*nata.*/i}});
{ "_id" : ObjectId("515ca5ae341398307500000f"), "created_at" : ISODate("2013-04-03T21:57:02Z"), "followed_by" : [ ObjectId("51558df4341398c509000000") ], "name" : "natafa", "updated_at" : ISODate("2013-04-20T16:42:40Z") }

Is this a bug?

Minification, Manual join(), custom Migration Class, Events, Validation

we're looking into forking and putting in something like this for minification:
https://github.com/marcqualie/mongominify/wiki/Getting-Started

creating a chainable ->join() method for joining other collections into the current object that relates the models id back to the joined model
ergo Users::find(array('name'=>'jackson'))->join( 'Posts' ) would take users _id and try to match it up in Posts user_id.

adding a custom migration class to replace the original one to use mongo as migration data/information storage.

adding events:
beforeCreate
beforeCreateNew
afterCreate
afterCreateNew
beforeSave
beforeSaveNew
afterSave
afterSaveNew
beforeValidation
afterValidation
beforeDestroy

Validation for Mongo: https://github.com/navruzm/laravel-mongo-validation

any plans on your side to do this?

pagination

is it possible to use original Laravel pagination with mongolid?

Does not install if mongodb is not running on same host

Output when doing composer install if mongodb is not running on same host. Same result even if default config has been provided for different host in database.php

Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Nothing to install or update
Generating autoload files
{"error":{"type":"ErrorException","message":"Failed to connect with string: "mongodb://127.0.0.1:27017/mongolid"","file":"/home/jscore/webhosts/jscore_ent_api/vendor/zizaco/mongolid/src/Zizaco/Mongolid/MongoDbConnector.php","line":30}}Script php artisan optimize handling the post-install-cmd event returned with an error

[RuntimeException]
Error Output:

install [--prefer-source] [--prefer-dist] [--dry-run] [--dev] [--no-dev] [--no-custom-installers] [--no-scripts] [--no-progress] [-v|vv|vvv|--verbose] [-o|--optimize-autoloader]

Delete function Issue

Hi there.

I just found an issue on delete function.
Here is the code:

$Model = new \Content\Models\Blocks;
$data = $Model->find( "52ebb8d407983b3816000000" );
$data->delete();

It finds the object fine and on delete returns true, but doesn't delete the object.
This issue happens when you have an object embeded with empty content like this:

{
  _id: ObjectId("52ebb8d407983b3816000000"),
  name: "TestClient",
  data: {},
  token: "TestClient",
  created_at: ISODate("2014-01-31T14:53:08Z"),
  updated_at: ISODate("2014-01-31T14:53:08Z")
}

(data: {}) generates the issue, if you remove that attribute, then delete works fine.

To make sure it's a mongolid issue I did a direct delete to the database using Mongo-PHP ->remove function and it worked properly.

Thanks in advance.

fail writing binary data to MongoDB document

Hi,

I was trying to embed a jpeg avatar image into my User document.
However after upload, trying to assign binary data image to $user->avatar and then doing $user->save() gives me:

{"error":{"type":"ErrorException","message":"json_encode(): Invalid UTF-8 sequence in argument","file":"\/var\/www\/l4angular\/vendor\/filp\/whoops\/src\/Whoops\/Handler\/JsonResponseHandler.php","line":103}}

doing bson_encode writes incorrect data to document, I think.
I can't give you exact code here, because it doesn't make much sense, but try writing binary jpeg data to MongoDB document, and then you'll see what happens.

It has been reported elsewhere on the internet that json_encode breaks with non-UTF-8 data. But is there a workaround this? Is there a way to write binary data from a jpeg image to a MongoDB document, and then later retrieve it and serve it as an image?
Please help and thank you very much.

embed One-to-Many More of a doubt..

Hi
i am presently creating a website where i have posts and have tags for each post which can be one-to-many relation with the posts. The way i am trying to do is as follows

class Post extends MongoLid {

    protected $collection = 'posts';

    public function categories(){

        return $this->embedsMany('Category', 'categories');
    }

}

Class Category:

class Category extends MongoLid
{

protected $collection = null;

}

Postcontroller :

$postid = Input::get('postid');

            $post = Post::find($postid);

            try
            {

                $post->description = Input::get('description');

                $post->caption = Input::get('caption');

                    $categories= array("action", "comedy");


                    foreach($categories as $category)
                    {

                         $post->categories = $category;

                                                //this is not working too
                                            $post->embedToCategories($category);

                    }



                $post->save();  

it throws me an error saying the following:

"Method save does not exist in OdmCursor nor in MongoCursor".

Selects!

How do I do selects? e.g. ->select('first_name');

save() not working for Users

Hi Zizaco,

I have two model classes. One is User, other is Company

class User extends ConfideMongoUser {
...
}

and

class Company extends MongoLid {
...
}

I also have a profile update method in both User and Company controller classes, which is almost identical:

class UserController extends BaseController {
public function postProfileUpdate() 
    {
        $userid = Auth::user()->_id;
        $user = User::first(new MongoId($userid));
        $input = Input::all();       
        $user->$input['name'] = $input['value'];
        if ($user->save(true))
            return 'success';
        else
            return 'fail';
    }
...
}

and

class CompanyController extends BaseController {
public function postProfileUpdate() 
    {
        $companyid = Auth::user()->company_id;
        $company = Company::first(new MongoId($companyid));
        $input = Input::all();     
        $company->$input['name'] = $input['value'];        
        if ($company->save(true))
            return 'success';
        else
            return 'fail';
    }
...
}

I checked everything 10 times, the only difference is that the User model extends ConfideMongoUser and the Company model extends MongoLid

The same postProfileUpdate method fails on save() for User and succeeds for Company.

Is there an error?

Thanks a LOT.

20 documents limit?

Is there a limit of returning 20 documents per query in MongoLid?

this code

public function index() 
    {
        $posts = Post::find(['created_by_user' => Auth::user()->_id]);
        return Response::json($posts->toArray());
    }

returns only 20 results, although there's more than 20 documents in collection.

Error in Docs

I think there's an error here in README.md:

Querying Using MongoLid Models

    $users = User::where(['votes'=>'$gt'=>[100]])->limit(10);

    foreach ($users as $user)
    {
        var_dump($user->name);
    }

MongoLid Count

    $count = User::where(['votes'=>'$gt'=>[100]])->count();

The error is in the placement of the left square bracket in both query lines. The left square bracket [ should be before '$gt', like this:

User::where(['votes'=>['$gt'=>100]])

Database [mongodb] not configured.

InvalidArgumentException
Database [mongodb] not configured.

/home/irto/Projetos/www/phonerio/vendor/laravel/framework/src/Illuminate/Database/DatabaseManager.php : 171

It's seem that Illuminate\Validation\Validator try to use a Driver for verify if tha field is unique on database.

PHP Syntax Parse Error

I'm getting a syntax error when i load your driver.

PHP Parse error: syntax error, unexpected '[' in /var/www/laravel/vendor/zizaco/mongolid/src/Zizaco/Mongolid/Model.php

I'm not sure what's causing it at all. Installed with Composer. Running on Ubuntu 12.10 with the latest apache2 and PHP5 available, along with the latest Mongo client available.

screenshot on 6 1 2013 at 3 34 55 pm

Embeds many find

$comments = Post::find('4af9f23d8ead0e1d32000000')->comments()->find($id);
how can i use above?

Friendly Issue

Ok, so there's no issue, feel free to close.

I just wanted to say how clean this is. Love how you've kept it as close to Eloquents syntax and layout as possible. Great work buddy.

Confirmation field not removed before saving to database

In commit 07a5732 you added removal of confirmation attributes before saving to a database, however it does not work for me.

I think that the issue is that

$confirmationField = $attr.'_password_confirmation';

should be

$confirmationField = $attr.'_confirmation';

Regex example

Hey there!

How would I replicate this using your package?

db.users.find({'$or':[{first_name: { $regex: /chris/i }}, {last_name: { $regex: /chris/i }}]});

Thanks!

Unique validator rule failing

The application crashes when using the unique validator rule, trying to use the app default database config

/**
* Validation rules
*/
    public static $rules = array(
        'email' => 'required|email|unique:users',
        'password' => 'required|between:8,50|confirmed',
        'api_key' => 'unique:users',
    );
[Exception]                                                                  
  SQLSTATE[HY000]: General error: 1 no such table: users (SQL: select count(*  
  ) as aggregate from "users" where "api_key" = ?) (Bindings: array (          
    0 => 'QHwLIgEVtYeScGKy22kxvX7YlSvvxZTZ',                                   
  )) 

Is it possible to have it implemented or should we use an alternate logic to prevent duplicates ?

How to update Document, embed?

User embed one profile...

Update....

$user = Auth::user();
$profile = $user->profile();
$profile->name = "Pepe";
$user->save();
return Auth::user()->profile();

But... not update :/

How to update a subdocument?

Mongolid crashes laravel when mongod crashes

hey Zizaco
i don't know is this a bug or some error on my part but i think this is a serious error when laravel loads it opens a new mongodb connection . Everything work fine until mongodb crashes after mongodb crashes laravel crashes too with following error

MongoClient::__construct(): send of 58 bytes failed with errno=10054 An existing 
connection was forcibly closed by the remote host

and refuses to load thereafter until apache server is restarted . After web server is restarted with mongodb running eveything works fime until mongodb crashes again

i don't know whats wrong please help
thank you

Multiple databases

MongoLid looks great, however I can't seem to see from the documentation if it's possible to configure multiple database connections and choose which database each model would use?

Seed

what's the easiest way to use mongolid to seed data with artisan?

thanks!

syntax error, unexpected '['

Followed the instructions and setup mongolid as described in the README.
Any thoughts if this is something on the implementation end, or in the MongoLid code?

I've attached a screenshot of the error.

screen shot 2013-06-01 at 8 32 19 pm

OR on where

Trying to create this query:

db.users.find({'$or':[{first_name: { $regex: /chris/i }}, {last_name: { $regex: /chris/i }}]});

How would I do that currently got:

$result = $user->where(array(['first_name' => ['$regex' => $regexp ]], ['last_name' => ['$regex' => $regexp ]]));

Usage of detach and polymorph

Please how to use the polymorphism in MongoLid ? I have a class Section and Question which inherit of another one class Item. Section and Question document must be saved into the same collection with a field display which contains "question" if it's a Question document and "section" if it's a Section document.
How to implement it please ?

I have a document call Item create by an User. I use referencesMany to save the reference of the document created by the user connected. The problem is when I want to deleted the Item created by the user and delete the reference in the document User. How to do it please ?

Thanks...

Composer update giving a Runtime exception

PHP Parse error: syntax error, unexpected '[' in /var/www/rfid/vendor/zizaco/mongolid-laravel/src/Zizaco/MongolidLaravel/MongoLid.php on line 294
{"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","message":"syntax error, unexpected '['","file":"/var/www/rfid/vendor/zizaco/mongolid-laravel/src/Zizaco/MongolidLaravel/MongoLid.php","line":294}}Script php artisan clear-compiled handling the post-update-cmd event returned with an error

[RuntimeException]
Error Output: PHP Parse error: syntax error, unexpected '[' in /var/www/rf
id/vendor/zizaco/mongolid-laravel/src/Zizaco/MongolidLaravel/MongoLid.php o
n line 294

Not sure what's going wrong. Any help is appreciated.

Thanks

Fillable and Guarded properties doesn't work

Getting below error for fillable and guarded properties. I tried with public access specifier it doesn't white/Black list the attributes.

Access level to Vibration::$fillable must be public (as in class Zizaco\MongolidLaravel\MongoLid)

I have model definition as below

<?php


class Vibration extends MongoLid {

    protected $collection = 'vibration';

    protected $fillable = array('sensor_id','package_id','truck_id');
}

?>

getGridFS() ?

Hello there,

I want to ask how do you store an image using your plugin? How do you get an instance of GridFS?

Does saving a document rewrite the whole document?

having a post document and having 10K comments embeded or even references in a comments array attribute, does saveing the document rewrite everything?
or even modifying only the comments attribute rewrite the whole 10K comments on the document?

Error when install

get error when install this libs. Help me check it.
in composer.json
"require": {
"laravel/framework": "4.1.*",
"zizaco/mongolid-laravel": "dev-master"
},
[root@MyWeb laravel]# composer update
Warning: This development build of composer is over 30 days old. It is recommended to update it by running "/usr/bin/composer self-update" to get the latest version.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- The requested package zizaco/mongolid-laravel could not be found in any version, there may be a typo in the package name.

Potential causes:

Read http://getcomposer.org/doc/articles/troubleshooting.md for further common problems.

syntax error, unexpected '['

i got the error in this file "zizaco\mongolid\src\Zizaco\Mongolid\Model.php" on line 489 and 492.
modified "[]" to null and it's ok.

ps:php 5.3,laravel 4

Observers

Does MongoLid support model observers?

How do you handle not found documents?

For example, i'm building a controller method that shows a form to edit a document. That document is referenced by _id using a url parameter which can obviously be tampered with by the user.

How can i actually detect that i found something or not in the cursor?

$editedAsset = AssetType::find($id);

I tried

if(count($editedAsset) != 1) //But it works only when i find something
if($editedAsset->count() != 1) //But it works only when i don't find anything

So i'm stuck here trying to find a way to throw the

App::abort(404)

In the correct circumstance, but i can't seem to find anything to do it...

Embed-Many querying

Hi, is it possible to find a embedded document to do an update (for example), because im trying to do a simple $ad->images()->find(1234); and it throws me a Call to a member function find() on a non-object. if is possible to query in the embedded documents?? or there's another way to achieve this.

Thanks.

auth driver not working

InvalidArgumentException
Driver [mongoLid] not supported.

I don't know if this is related to the other issue I posted.

The $hidden property in Models isn't taken into account

Hello,

Eloquent models have a $hidden property that allows to exclude a list of specific fields from being dumped in an array or JSON conversion. It is documented in the Eloquent docs.

In Mongolid, every field seems to be dumped in arrays or JSON conversions, even though I did set a list of fields in the $hidden property.

// Basic model
class User extends MongoLid implements UserInterface
{
    public $hidden = array('_id', 'password');
}

// Instance
$myUser = User::where(['email' => '[email protected]'])->first();

// Data dump as JSON
dd($myUser->toJSON());

// Fields '_id' and 'password' are dumped even though they're listed in the $hidden property
// {"_id":{"$id":"52f4b1b1140ba0ee61c5bce8"},"email":"[email protected]","password":"$2y$10$eVn5tr1vKiwYtRTKM9sRWOXqC1LEFoCxX1LmsLUWZqr2Pv8TSk4AC"}

Is there something I don't get ? Or is it an issue ?

Thanks in advance.

composer install problem

Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
- Installation request for zizaco/mongolid-laravel dev-master -> satisfiable by zizaco/mongolid-laravel[dev-master].
- zizaco/mongolid-laravel dev-master requires zizaco/mongolid dev-master -> no matching package found.

About Model::referencesMany($model, $field, $cachable = true)

Thank you for your good library.

I used referencesMany() in my Mongolid class. I defined correctly?
For a typical relationship example in http://docs.mongodb.org/manual/core/data-modeling-introduction/#references, I defined following.

class User extends Mongolid {
    protected $collection = 'Users';
    public function contacts(){
        return $this->referencesMany('Contact', '_id');
    }
}

But it was not good, interpreter said

Symfony \ Component \ Debug \ Exception \ FatalErrorException
Cannot use object of type MongoId as array

at line 553 in Model.php.

Did I use it correctly? Any hints, please.

ReferencesMany Doesn't work with ConfideMongoUser?

My Models:

referencesOne('User','author'); } } ?> referencesMany('Post', 'posts'); } /** * Get the unique identifier for the user. * * @return mixed */ public function getAuthIdentifier() { return $this->_id; } /** * Get the password for the user. * * @return string */ public function getAuthPassword() { return $this->password; } ``` } ?>

-------------- Routes

Create a Post attach User:

Route::get('/post', function(){
$post = new Post();
$post->title = "Titulo de un Diario";
$post->body = "Este es el contenido del diario";
$post->attach('author', Confide::user());
$post->save();
});

Retrive post from session user:

Route::get('/my/posts', 'UserController@showPosts');

------ Controller

public function showPosts(){
var_dump( Confide::user()->posts() );
}

OUTPUT localhost/user/my/posts: (declarated route)

array(0) { }

OUTPUT MONGO:

db.posts.find()

{ "_id" : ObjectId("526bd48827602e06308b4568"), "title" : "Titulo de un Diario", "body" : "Este es el contenido del diario", "author" : [ ObjectId("5269ab5427602e704f8b4567") ], "created_at" : ISODate("2013-10-26T14:41:12.451Z"), "updated_at" : ISODate("2013-10-26T14:41:12.451Z") }

Can you help me?

extends mongolid or mongoLid

Hi Zizaco,

In some examples of code you extends monglid but in others you use mongoLid.

Which is the right one?

Thanks

Novice questions!

How do you do $or statements with where()?

How do you do select()?

Class 'MongoClient' not found in ...

hi i'm also getting this error:
/vendor/zizaco/mongolid/src/Zizaco/Mongolid/MongoDbConnector.php","line":28
Symfony\Component\Debug\Exception\FatalErrorException","message":"Class 'MongoClient' not found

i've tried everything —uninstalled and reinstalled the driver many times, but the error persists.

the strange thing is that phpinfo shows mongo is loaded, but i tried grepping the extension and it returns nothing. i did a: 'which php' and it returns the correct cli. any ideas what is going on here?

The "created_at" and "updated_at" automatic timestamps can't be disabled

Hello,

Eloquent models have a $timestamps property that can be set to false in order to disable the automatic timestamp feature.

In Mongolid the fields "created_at" and "updated_at" seem to be added to every record I create, even though I did set the $timestamp property to false.

Is there something I don't get ? Or is it an issue ?

Thanks in advance.

composer error MongoClient class missing

Here's composer error I get:

PHP Fatal error: Class 'MongoClient' not found in /var/www/l4angular/vendor/zizaco/mongolid/src/Zizaco/Mongolid/MongoDbConnector.php on line 30
{"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","message":"Class 'MongoClient' not found","file":"/var/www/l4angular/vendor/zizaco/mongolid/src/Zizaco/Mongolid/MongoDbConnector.php","line":30}}Script php artisan optimize handling the post-update-cmd event returned with an error: PHP Fatal error: Class 'MongoClient' not found in /var/www/l4angular/vendor/zizaco/mongolid/src/Zizaco/Mongolid/MongoDbConnector.php on line 30

Add ArrayAccess to MongoLid class

Since we are not able to use an instance of MongoLid in the Form::model() function, implementing the ArrayAccess interface in MongoLid class solves this issue.

I would like to submit a pull request, but this repository don't allow forks.

Database name issue

There seems to be an issue setting the name of the database.

No matter what i set in the database.php, it connects to mongolid database.

vendor\zizaco\mongolid-laravel\src\MongolidServiceProvider.php - $connectionString returns:
mongodb://host:port/collection

vendor\zizaco\mongolid\src\MongoDbProvider.php - $connectionString returns:
mongodb://host:port/collection

but

vendor\zizaco\mongolid-laravel\src\MongoLib.php - $this->database returns:
mongolid

vendor\zizaco\mongolid-laravel\src\MongoLib.php - $this->collection returns:
mycollection

Everytime i try and use the ODM, it always references mongolid instead of what i specified and i can't seem to find out why.

I fixed this by removing if(!$this->database){ from mongolid.php, but i'm not sure if this is a proper fix.

Timestamp attribute is useless

I can't create automated timestamps and do it manually. can u implement eloquent like timestamp model its very helpful, otherwise module is ultimate......

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.