GithubHelp home page GithubHelp logo

moloquent / moloquent Goto Github PK

View Code? Open in Web Editor NEW

This project forked from mongodb/laravel-mongodb

121.0 16.0 37.0 1.16 MB

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

Home Page: https://moloquent.github.io

PHP 100.00%

moloquent's Introduction

Moloquent (Laravel MongoDB)

Latest Version Downloads Build Status Coverage Status Donate

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.

Getting Started

Just go ahead to Documentation to get started using this library.

Who are we ?

The base repo WAS and IS being developed and maintained by Jenssegers. Our goal is to provide higher quality support/bugfixes with fresh and additional features.

moloquent's People

Contributors

alexandre-butynski avatar arogozin avatar bodom78 avatar codeclown avatar daveawb avatar dgreda avatar dimasdanz avatar dschreck avatar duxet avatar hannesvdvreken avatar j-ibarra avatar jdsingh avatar jenssegers avatar joeyhoutenbos avatar khamkham avatar loonytoons avatar mahdi-acto avatar mlanin avatar morrislaptop avatar moura137 avatar mrletrunghieu avatar pi0 avatar ricardoaponte avatar ricardofontanelli avatar rjvandoesburg avatar rtler avatar ryanwinchester avatar tacone avatar thiagocarnaes avatar v-six 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

moloquent's Issues

MongoDB connection pool

Hi, I got a weird issue regarding connection pool.
I have a MongoDB Atlas server with 350 concurrent connections.
I have built with Laravel a small app which uses Moloquent and Mongo DB for crud operations.
My problem is that everytime a user makes requests to the app, and has to do something into MONGO, the driver creates a new connection, and stay open until I restart phpfpm.

Any idea how to close the connection?

Passport: Issuing Personal Access Tokens is Not Working

There is an error when trying to issue a new personal access token, as described at https://laravel.com/docs/5.5/passport#personal-access-tokens

Running:

$token = User::find('59d63bab106a6c766568e3c9')->createToken('My Token', ['place-orders'])->accessToken;

Error: Trying to get property of non-object

File: /www/dev.app/vendor/laravel/passport/src/ClientRepository.php

Method:
75. public function personalAccessClient()
76. {
77. if (Passport::$personalAccessClient) {
78. return $this->find(Passport::$personalAccessClient);
79. }
80.
81. return PersonalAccessClient::orderBy('id', 'desc')->first()->client;
82. }

Full Stack:

dev.ERROR: Trying to get property of non-object {"userId":"59c4ed25106a6c1c4734d43e","exception":"[object] (ErrorException(code: 0): Trying to get property of non-object at /www/dev.app/vendor/laravel/passport/src/ClientRepository.php:81)
[stacktrace]
#0 /www/dev.app/vendor/laravel/passport/src/ClientRepository.php(81): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8, 'Trying to get p...', '/www/dev.app/...', 81, Array)
#1 /www/dev.app/vendor/laravel/passport/src/PersonalAccessTokenFactory.php(71): Laravel\Passport\ClientRepository->personalAccessClient()
#2 /www/dev.app/vendor/laravel/passport/src/HasApiTokens.php(67): Laravel\Passport\PersonalAccessTokenFactory->make('59d63bab106a6c7...', 'My Token', Array)
#3 /www/dev.app/routes/codi-app.php(92): App\Models\BaseModelAuth->createToken('My Token', Array)
#4 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Route.php(198): Illuminate\Routing\Router->{closure}()
#5 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Route.php(172): Illuminate\Routing\Route->runCallable()
#6 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Router.php(645): Illuminate\Routing\Route->run()
#7 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(30): Illuminate\Routing\Router->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#8 /www/dev.app/vendor/laravel/passport/src/Http/Middleware/CreateFreshApiToken.php(48): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#9 /www/dev.app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Laravel\Passport\Http\Middleware\CreateFreshApiToken->handle(Object(Illuminate\Http\Request), Object(Closure))
#10 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#11 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php(41): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#12 /www/dev.app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\Routing\Middleware\SubstituteBindings->handle(Object(Illuminate\Http\Request), Object(Closure))
#13 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#14 /www/dev.app/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php(67): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#15 /www/dev.app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\Foundation\Http\Middleware\VerifyCsrfToken->handle(Object(Illuminate\Http\Request), Object(Closure))
#16 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#17 /www/dev.app/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php(49): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#18 /www/dev.app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\View\Middleware\ShareErrorsFromSession->handle(Object(Illuminate\Http\Request), Object(Closure))
#19 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#20 /www/dev.app/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(63): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#21 /www/dev.app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\Session\Middleware\StartSession->handle(Object(Illuminate\Http\Request), Object(Closure))
#22 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#23 /www/dev.app/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php(37): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#24 /www/dev.app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse->handle(Object(Illuminate\Http\Request), Object(Closure))
#25 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#26 /www/dev.app/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(59): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#27 /www/dev.app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\Cookie\Middleware\EncryptCookies->handle(Object(Illuminate\Http\Request), Object(Closure))
#28 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#29 /www/dev.app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(102): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#30 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Router.php(647): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#31 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Router.php(622): Illuminate\Routing\Router->runRouteWithinStack(Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request))
#32 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Router.php(588): Illuminate\Routing\Router->runRoute(Object(Illuminate\Http\Request), Object(Illuminate\Routing\Route))
#33 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Router.php(577): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request))
#34 /www/dev.app/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(176): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request))
#35 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(30): Illuminate\Foundation\Http\Kernel->Illuminate\Foundation\Http\{closure}(Object(Illuminate\Http\Request))
#36 /www/dev.app/app/Http/Middleware/codi/SetDB.php(103): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#37 /www/dev.app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): App\Http\Middleware\codi\SetDB->handle(Object(Illuminate\Http\Request), Object(Closure))
#38 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#39 /www/dev.app/vendor/fideloper/proxy/src/TrustProxies.php(56): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#40 /www/dev.app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Fideloper\Proxy\TrustProxies->handle(Object(Illuminate\Http\Request), Object(Closure))
#41 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#42 /www/dev.app/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(30): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#43 /www/dev.app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle(Object(Illuminate\Http\Request), Object(Closure))
#44 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#45 /www/dev.app/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(30): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#46 /www/dev.app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle(Object(Illuminate\Http\Request), Object(Closure))
#47 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#48 /www/dev.app/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php(27): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#49 /www/dev.app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\Foundation\Http\Middleware\ValidatePostSize->handle(Object(Illuminate\Http\Request), Object(Closure))
#50 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#51 /www/dev.app/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php(46): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#52 /www/dev.app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode->handle(Object(Illuminate\Http\Request), Object(Closure))
#53 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#54 /www/dev.app/vendor/barryvdh/laravel-cors/src/HandlePreflight.php(46): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#55 /www/dev.app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Barryvdh\Cors\HandlePreflight->handle(Object(Illuminate\Http\Request), Object(Closure))
#56 /www/dev.app/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#57 /www/dev.app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(102): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#58 /www/dev.app/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(151): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#59 /www/dev.app/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(116): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request))
#60 /www/dev.app/public/index.php(55): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request))
#61 {main}
"}

tagged version

Hi guys,

when do you plan to release the next version?

Kind regards

Michael

Moloquent Support.php breaks Laravel optimization

When you run php artisan optimize it creates compiled.php file that contains all of the Laravel basic classes and interfaces, so that using them doesn't require searhing and autoloading the exact file.

Thing is composer autoloads static php files defined in composer packages first. And in your SupportClasses/Support.php there is an explicit load of Moloquent model that fires autoloading lots of Laravel's and Moloquent's additional interfaces and classes BEFORE Laravel loads them from compiled.php.

And this makes php die with fatal error:

PHP Fatal error:  Cannot declare interface Illuminate\Contracts\Support\Arrayable, because the name is already in use in /home/vagrant/project/bootstrap/cache/compiled.php on line 140

This problem makes using optimisation impossible!

One more thing. Composer fires optimize command from post-install and post-update scripts, so this issue WILL break any project that will install it's packages on production environment (situation I had today).

Using outside laravel with packages 5.5

When i used this package outside laravel, i received this error:
Call to a member function all() on array

On this line:
image

Capsule instance code:

$config = $container->get('config')['datasource']['mongodb'] ?? false;

        if (!$config) {
            throw new \InvalidArgumentException('Check \'datasource\' key, have \'mongodb\' config ?');
        }

        $capsule = new Capsule();
        $capsule->addConnection($config);
        $capsule->getDatabaseManager()->extend('mongodb', function($config){
            return new Connection($config);
        });
        $capsule->bootEloquent();
        return $capsule;

My code:

return new JsonResponse(AuthRepository::all())

Query Builder error

github_report
I'm using a mixed databases, mysql is the default and mongodb the second.
My only 2 classes looks like this:

User: (pretty much a normal model beside the replace of the use Moloquent\Eloquent\Model)

<?php

namespace App;

use Moloquent\Eloquent\Model as Moloquent;

class User extends Moloquent
{
    protected $connection = 'mysql';
    protected $table = 'users';
    ...

Post:

<?php

namespace App;

use Moloquent\Eloquent\Model as Moloquent;
use Moloquent\Eloquent\HybridRelations;

class Post extends Moloquent
{
    use HybridRelations;
    protected $connection = 'mongodb';
    protected $collection = 'posts';
    ...

According with the stacktrace the erro comes from this line:
$user = User::where('email', $socialUser->email)->first();

I'm doing anything wrong?
Let me know if you want to see any other piece of the code.

Why this package over original?

Hello Guys,
I've been using the original package for almost a year now and recently found that other package. Why I should use this over the original one?? I'd like to know the benefits.

Thanks!

queue:work is not working.

ErrorException: Undefined property: Moloquent\Queue\MongoQueue::$expire in ........./vendor/moloquent/moloquent/src/Queue/MongoQueue.php:23

Getting above exception in every try. MongoDB jobs collection has jobs but none of them are processing by queue.

artisan migrate is broken due to missing grammar

Hi guys,

when I do a artisan migrate I got following error:

 [Symfony\Component\Debug\Exception\FatalThrowableError]         
  Call to a member function supportsSchemaTransactions() on null

It seems that the Schema grammar is not set properly.

Kind regards

Michael

migration:Index with name: email_1 already exists with different options

I have followed the steps from https://moloquent.github.io/master/ to use mongo db on laravel.
I have done a crud functionality. which works fine.

I have two migrations provided laravel by default

when i run php artisan:migrate it produces the error

In CreateIndexes.php line 100:

Index with name: email_1 already exists with different options

and also only user collection is created , and that password feild is not createrd
forgetpassword collection not created.

please help what i'm missing..

my migration files are.

Users migration file

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $collection) {
/$collection->increments('id');/
$collection->index('name');
$collection->index('email')->unique();
$collection->index('password');
/* $collection->rememberToken();/
/
$collection->timestamps();*/
});
}
public function down()
{
Schema::dropIfExists('users');
}
}

forgot password migration file

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePasswordResetsTable extends Migration
{
public function up()
{
Schema::create('password_resets', function (Blueprint $collection) {
$collection->index('email');
$collection->index('token');

    });
}
public function down()
{
    Schema::dropIfExists('password_resets');
}

}

User model file

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Moloquent\Eloquent\Model as Eloquent;
use DB;

class User extends Eloquent
{

protected $connection = 'mongodb';
protected $collection = 'users';


/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'email', 'password',
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];


public static function userslist($params)
{
    $users = User::all();

    return $users;
}

public static function userscreate($params)
{
    /*$b = User::create([ 'name' => $params['name'],'email' => $params['email'] ]);*/

     $newuser = new User;
     $newuser->name = $params['name']; 
     $newuser->email = $params['email'];
     $newuser->save();

    return true;
}

public static function usersupdate($params)
{
   $user = DB::collection('users')->where('_id', $params['_id'])
                   ->update(['name'=> $params['name'],
                            'email'=> $params['email']
                    ]);

    return $user;
}

 public static function usersdelete($params)
{
    $delete=DB::collection('users')->where('_id', $params['_id'])->delete();
    return $delete;
}

}

text search with WHERE clause?

Target: searching products in mongodb by 'name' field using full text search, ordered by 'textScore', where 'category' ='phones'. Can we get textScore value?

In Laravel I tried even whereRaw() static method without luck.

In mongodb I created this query (without the needed WHERE clause (from a specific category) because I don't know how to do this.

db.records.find(
{ $text: {$search: "android 4"},
},
{score: {$meta: "textScore"} },
)
.sort({score:{$meta:"textScore"}})

Any idea how the Laravel query should look like?

I created this query, but it's incomplete:
$records = Record::whereRaw(array('$text'=>array('$search'=> """ . 'my input' . """)))->get();

Incomplete because:

  1. results are not ordered by textScore.
  2. I don't know to add the where clause on the category=phones
  3. $records does not contain the value of 'textScore' to see if the score is good enough.

Any idea for this issue?

Update to Laravel 5.5

Hello everyone!

the next entry is to discuss the laravel 5.5 update

yesterday a small bug was fixed in HybridRelations.php

but I think that you have to make a new branch only for version 5.4 and the dev-master for the new version that can include the new laravel features to install the dependencies that the user does not have to configure the file config/app.php (please see this)

 "extra" : {
    "laravel" : {
        "providers" : [
            "Moloquent\\MongodbServiceProvider",
            "Moloquent\ \Auth\\PasswordResetServiceProvider",
            "Moloquent\\MongodbQueueServiceProvider",
            "Moloquent\\Passport\\PassportServiceProvider"
        ],
        "aliases" : {
           "Moloquent" : "Moloquent\Eloquent\Model"
        }
    }
 }

also I have achieved with a few bugs in the basic auth of laravel, missing the tails, the passport, and other tasks that may be involved the Moloquent

Laravel 5.5 Support

Error with new official released Laravel 5.5

Declaration of Moloquent\Eloquent\HybridRelations::belongsToMany($related, $collection = NULL, $foreignKey = NULL, $otherKey = NULL, $relation = NULL) should be compatible with Illuminate\Database\Eloquent\Model::belongsToMany($related, $table = NULL, $foreignPivotKey = NULL, $relatedPivotKey = NULL, $parentKey = NULL, $relatedKey = NULL, $relation = NULL)

Using other operators than $last for groupBy

I understand that the document says: Selected columns that are not grouped will be aggregated with the $last function. However in certain data manipulation cases this may not suitable. For Example, I need to pipeline that would group by and return the result with grouped key and another set of values in an array format.

I know I can do this using raw() but writing code in Eloquent style is much better. Did I skip some part of documentation or maybe there is an alternate way to do this? Can you help me find a better way than using raw()?

whereHas not working with belongsTo relationship

Using the relationship querying facilities like has('relationship') and whereHas('relationship', Closure) breaks with the error
Call to undefined method Moloquent\\Query\\Builder::getHasCompareKey()

Class 'Moloquent\Eloquent\Model' not found

I've been trying to use Moloquent as a service provider, I kept getting errors since I'm using the following paths in my code (config file and Eloquents):
Moloquent\MongodbServiceProvider::class
Moloquent\Auth\PasswordResetServiceProvider::class
Moloquent\Eloquent\Model

Edit:
I've changed

  • Moloquent\MongodbServiceProvider::class to Jenssegers\Mongodb\MongodbServiceProvider::class
  • and Moloquent\Auth\PasswordResetServiceProvider::class to Jenssegers\Mongodb\Auth\PasswordResetServiceProvider::class
  • and also Moloquent\Eloquent\Model to Jenssegers\Mongodb\Eloquent\Model

and everything is normal.

Save method creating multiple records in collection

Hi,
I am using below code to save entry to a collection, however after save method is executed, the entries are inserted twice with unique "id" in the mongodb database.

$i = new MyInfo();
    $i->name = $n;
    $i["step-1"] = $s1;
    $i["Step-2"] = $s2;
    $i["additional"] = $a;
    $i->Save();
    echo "Saved";

Passport middleware is not working

Even after passing the Authorization: Bearer in the header the request always returns unauthenticated with the auth:api middleware.

Well i figured out passport wasn't setup properly but now we have ran into another issue.

We get the following error.

`BadMethodCallException in Builder.php line 2508:
Call to undefined method Moloquent\Query\Builder::withAccessToken()

in Builder.php line 2508
at Builder->__call('withAccessToken', array(object(Token))) in Builder.php line 1157
at Builder->__call('withAccessToken', array(object(Token))) in Builder.php line 1332
at Builder->__call('withAccessToken', array(object(Token))) in Model.php line 1316
at Model->__call('withAccessToken', array(object(Token))) in Model.php line 590
at Model->__call('withAccessToken', array(object(Token))) in TokenGuard.php line 139
at TokenGuard->authenticateViaBearerToken(object(Request)) in TokenGuard.php line 90
at TokenGuard->user(object(Request)) in PassportServiceProvider.php line 251
at PassportServiceProvider->Laravel\Passport{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in RequestGuard.php line 54
at RequestGuard->user() in GuardHelpers.php line 49
at RequestGuard->check() in Authenticate.php line 61
at Authenticate->authenticate(array('api')) in Authenticate.php line 41
at Authenticate->handle(object(Request), object(Closure), 'api') in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing{closure}(object(Request)) in ThrottleRequests.php line 49
at ThrottleRequests->handle(object(Request), object(Closure), '60', '1') in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing{closure}(object(Request)) in Pipeline.php line 102
at Pipeline->then(object(Closure)) in Router.php line 561
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 520
at Router->dispatchToRoute(object(Request)) in Router.php line 498
at Router->dispatch(object(Request)) in Kernel.php line 174
at Kernel->Illuminate\Foundation\Http{closure}(object(Request)) in Pipeline.php line 30
at Pipeline->Illuminate\Routing{closure}(object(Request)) in TransformsRequest.php line 30
at TransformsRequest->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing{closure}(object(Request)) in TransformsRequest.php line 30
at TransformsRequest->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing{closure}(object(Request)) in ValidatePostSize.php line 27
at ValidatePostSize->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing{closure}(object(Request)) in CheckForMaintenanceMode.php line 46
at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in Pipeline.php line 148
at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing{closure}(object(Request)) in Pipeline.php line 102
at Pipeline->then(object(Closure)) in Kernel.php line 149
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 116
at Kernel->handle(object(Request)) in index.php line 53`

Problem with search engine

Problems with accented searches.
I need to make a mongodb query that is indifferent to the accents.
For example: acción or accion and give me the same result.

Attributes are not loaded when using a dynamic property in many to many relations L5.4

Using Laravel 5.4, Modela related to Modelb using belongsToMany (and the same for Modela related to Modelb) the relation will push related ids to the documents. But here's the thing:
Using a dynamic attribute to retrieve the models, gives empty models containing only the _id attribute.

Modela:
public modelbs(){ return $this->belongsToMany('App\Modelb'); }

Modelb:
public modelas(){ return $this->belongsToMany('App\Modela'); }

Problem:
$instance = Modela::all()->first(); foreach($instance->modelbs as $m) echo $m->name; // Returns null

Schema::rename error by migration

  [Symfony\Component\Debug\Exception\FatalThrowableError]
  Type error: Argument 2 passed to Illuminate\Database\Schema\Blueprint::build() must be an instance of Illuminate\Database\Schema\Grammars\Grammar, null given, called in C:\OSPanel\domains\reporti
  ng-tool\vendor\laravel\framework\src\Illuminate\Database\Schema\Builder.php on line 239
    public function up()
    {
        Schema::rename('reports_column_lists', 'databases');
        Schema::rename('reports_column_list_items', 'databaseItems');
        Schema::rename('reports_column', 'fields');
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }

Password Reset Service Provider

hello everyone, I have some problem when I try reset e password

FatalThrowableError in DatabaseTokenRepository.php line 58:
Type error: Argument 2 passed to Illuminate\Auth\Passwords\DatabaseTokenRepository::__construct() must implement interface Illuminate\Contracts\Hashing\Hasher, string given, called in /home/jcs/Documentos/docker/applaravel/vendor/moloquent/moloquent/src/Auth/PasswordBrokerManager.php on line 22

I register this included service provider

Moloquent\MongodbServiceProvider::class,
Moloquent\Auth\PasswordResetServiceProvider::class,

I use make:auth to Laravel's native Auth functionality

I can register, login and logout

image

Error when calling belongsToMany-relationship

I am getting this error Call to undefined method Moloquent\Query\Builder::getBelongsToManyCaller() when calling $menu->organisations().

The relationship in the menu-model is defined as:

	public function organisations()
	{
		return $this->belongsToMany(Organisation::class);
	}

I am using the "dev-master"-branch.
The method is being called from Moloquent\Eloquent\HybridRelations line 234. The problem seems related to Laravel 5.4 compatibility as discussed here: #49

Work-around for this problem is to define the relationship as:

	public function organisations()
	{
		return $this->belongsToMany(Organisation::class, null, null, null, 'organisations');
	}

But when using attach-method, this error occurs Undefined property: Moloquent\Relations\BelongsToMany::$otherKey.

Also take a look at this: mongodb#1108

New Release date for changes related to laravel 5.4

Hi,
There are many changes related to relationships and queue are done for Laravel 5.4.
When are you going to release those changes?

If not soon then what is the alternative to use in production as well as a development environment?

Compatibility with Laravel Passport is broken.

Hi guys,

I ran into the following issue using passport and moloquent:

When checking the Toking I got 'unauthorized' response because of an technical error. After some debugging I found that the Token class is inherited from Illuminate\Database\Eloquent\Model;. If I change this to use Moloquent\Eloquent\Model; it works as expected. Can you introduce an adjusted Token class and override the original one?

Thanks in advance

Michael

Auth::attempt not working

im trying to implement a customized login via ajax but using the Auth::attempt seems to fail

Call to a member function compileSelect() on null in /home/ivan/repos/primo-server/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:1652 

User Class

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

[Proposal] Rebase with upstream

It is a while that we miss some upstream updates. (Currently 19 commits behind)
Changes may be applied using custom patches as we have lots of changes/improvements and namespace changes here.

TODO: [WIP]

  • listing changes
  • specify and apply critical patches
  • ...

Could not find package moloquent/moloquent at any version

$ composer require moloquent/moloquent

  [InvalidArgumentException]
  Could not find package moloquent/moloquent at any version for your minimum-stability (stable).
  Check the package spelling or your minimum-stability

and

$ composer require moloquent/moloquent:dev-master

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

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://getcomposer.org/doc/04-schema.md#minimum-stability> for more details.

Read <https://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

[Question] how to change/set the type of a field ?

am sorry to bother u again but am currently trying to make a query where it searches for a field of some_name and change/set its type to something else , is this even possible ?

here is what i have so far

$tables = DB::getMongoDB()->listCollections();

// update the field on each collection
foreach ($tables as $one) {
    $name = $one->getName();
    DB::table($name)->find($field)->set([
       // ...
    ]);
}

this is mostly a part of a tool am creating to help migrate data to mongo from mysql as easy as possible, u can check it in here https://github.com/ctf0/MysqlToMongoDb

$appends for embedded models

I have three models, one embeds the other as below:

class File extends \Moloquent
{
    public function property()
    {
        return $this->embedsOne(Property::class);
    }
}

class Property extends \Moloquent
{
    public function address()
    {
        return $this->embedsOne(Address::class);
    }
}

class Address extends \Moloquent
{
    protected $appends = ['zipCode'];

    public function getZipCodeAttribute()
    {
        return $this->zipCodeBase . ($this->zipCodeExt != '' ? '-'.$this->zipCodeExt : null);
    }
}

The problem is that when I return json response with File model, the json result does not include appended properties from Address model.

However, if I move up one level (inside File) the Address model this problem does not exist, so I think that is caused by multi-level nesting.

Moloquent seem to break in Laravel release 5.4.19

Running my unit tests (normal CRUD operations) on moloquent models emit the following error:

1) Tests\Feature\Api\DataPointTest::testShowDataPointForbidden
Symfony\Component\Debug\Exception\FatalThrowableError: Type error: Argument 1 passed to Moloquent\Query\Builder::__construct() must be an instance of Moloquent\Connection, instance of Illuminate\Database\MySqlConnection given, called in /my-project/vendor/moloquent/moloquent/src/Eloquent/Model.php on line 560

I suspect a relation to the issue laravel/framework#18837 wich seems to be introduced by laravel/framework#18769.

hasOne & hasMany not working with foreignKey in ObjectId

hasOne & hasMany not working with foreignKey in ObjectId

Example:

User {
_id: ObjectId('dfsfasdhfj4252345hasdjklfsdf')
name: 'Alex'
}
Sale {
_id: ObjectId('asdfasdf8789a7sdf9adfasf'),
idUser: ObjectId('dfsfasdhfj4252345hasdjklfsdf')
}

in User class:

public function sales()
{
    return $this->hasMany(Sale::class, 'idUser', '_id');
}

and -> $user->sales

result: []

Setting $primaryKey to NULL causes internal server error

Within embedded documents, I'd like to disable $primaryKey's. From what little base Laravel knowledge I have, i know this is possible by overwriting them in your model like this:

protected $primaryKey = null;

However, if i try that with a model that extends Moloquent\Eloquent\Model I get a blank page, with a 500 (internal server error) status code. From what very little debugging i could try with this exception, I couldn't find anything, since it doesnt pass through Laravels ExceptionHandler.

This is an example of one of the models where I'm attempting to disable ID's:

class Color extends AbstractModel
{
    public $timestamps = false;
    protected $primaryKey = null;
    protected $fillable = [
        'hex', 'name',
    ];
}

Note: AbstractModel extends Moloquent\Eloquent\Model.

Is this a known bug, or is there an undocumented feature in Moloquent that'll let me accomplish this?

Thanks :)

[bug] with dates

the fields are saved as

  "created_at": new Date("2016-08-09T21:47:12+0200"),
  "updated_at": new Date("2016-09-30T14:36:55+0200")

doing something like dd(Article::first()->created_at); return

Carbon {#216 
  +"date": "2016-08-09 19:55:04.000000"
  +"timezone_type": 3
  +"timezone": "UTC"
}

setting the attr like

public function getCreatedAtAttribute($value)
    {
        return Carbon::parse($value)->toDateTimeString();
    }

return

DateTime::__construct(): Failed to parse time string (1470772504000) at position 12 (0): Unexpected character

using the hack from jenssegers/date#225 as "@{$value}" return "48576-12-03 21:46:40"

Laravel 5.4 with Moloquent give error when insert data

I have this error with moloquent/moloquent package.

composer require moloquent/moloquent

My Item class Model extended from Moloquent:

<?php

namespace App;

use Moloquent\Eloquent\Model as Eloquent;

class Item extends Eloquent
{
    protected $collection = 'items';
    protected $connection = 'mongodb';
...
}

My test to insert into items collection:

Item::create([
    'user_id' => 1,
    'title' => 'test',
    'slug' => 'test',
])

Result:

FatalThrowableError in Builder.php line 103: Type error: Argument 1
passed to Moloquent\Query\Builder::__construct() must be an instance
of Moloquent\Connection, instance of
Illuminate\Database\MySqlConnection given, called in
/home/site_com/http/www/vendor/moloquent/moloquent/src/Eloquent/Model.php
on line 560

Undefined variable: foreignKey, $otherKey

On running of migration (php artisan migrate) there comes the error Undefined variable: foreignKey, $otherKey, $collection. This applies to the method public function belongsToMany in moloquent/src/Eloquent/HybridRelations.php.

Thank for help

Insert create method doesn't works

Item::create(['name' => 'John']); doesn't works.

I use this method in my controllers...

Type error: Argument 1 passed to Moloquent\Query\Builder::__construct() must be an instance of Moloquent\Connection, instance of Illuminate\Database\MySqlConnection given, called in /home/site_com/http/www/vendor/moloquent/moloquent/src/Eloquent/Model.php on line 560

<?php

namespace App;

use Moloquent\Eloquent\Model as Eloquent;

class Item extends Eloquent
{
    protected $collection = 'items';
    protected $connection = 'mongodb';

...
}

Unit tests for CRUD operations failing on time stamp and dates

I'm trying to test my CRUD methods, but it failing because laravel TestCase Method assertDatabaseHas() cant compare the fields that uses timestamp o Date as type because it is converted to MongoDB\BSON\UTCDateTime, is there any work arround, coz now i'm excluding the created_at and updated_at fields, but i all so have other models that uses this datatype.

public function testUpdate(){
        $data = factory(Product::class)->create();
        $data->fill(factory(Product::class)->make()->toArray());
        $response = $this->put(route('products.update', $data), $data->toArray());
        $response->assertJson($data->toArray());
        $this->assertDatabaseHas($data->getTable(), $data->toArray());
    }
1) Tests\Feature\ProductControllerTest::testUpdate
Failed asserting that a row in the table [products] matches the attributes {
    "name": "CISCO Fire",
    "price": 5461.97,
    "description": "Ea eligendi qui qui debitis soluta nihil itaque. Quia laborum mollitia voluptatem. Aut corrupti excepturi vel quis ut. Architecto eaque voluptates quia enim in exercitationem nesciunt.",
    "updated_at": "2017-07-19 07:38:42",
    "created_at": "2017-07-19 07:38:42",
    "_id": "596f0c82d1f2d724aa03c11f"
}.

Found: [
    {
        "_id": {},
        "name": "ACER MURPHY",
        "price": 10722.72,
        "description": "Est ea et omnis nemo. Et iure ea accusamus distinctio omnis exercitationem. Sapiente et dignissimos eveniet et iusto quos explicabo. Tempore inventore corporis minima minus quibusdam.",
        "updated_at": {},
        "created_at": {}
    },
    {
        "_id": {},
        "name": "TOSHIBA Flame",
        "price": 1314.84,
        "description": "Omnis nisi iusto eum et. Nisi perferendis dolorem sed id et. Odit et sequi corporis necessitatibus error et consequatur.",
        "updated_at": {},
        "created_at": {}
    },
    {
        "_id": {},
        "name": "CISCO Fire",
        "price": 5461.97,
        "description": "Ea eligendi qui qui debitis soluta nihil itaque. Quia laborum mollitia voluptatem. Aut corrupti excepturi vel quis ut. Architecto eaque voluptates quia enim in exercitationem nesciunt.",
        "updated_at": {},
        "created_at": {}
    }
].

/home/ivan/repos/primo-server/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php:22
/home/ivan/repos/primo-server/tests/Feature/ProductControllerTest.php:40

Count on Moloquent

Hi,

How I can count values as $blog->articles->count() ?

The value returned is 0...

Thanks.

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.