1

I want to use MongoDB in Laravel. This is my code inside of the controller:

public function create (Request $request) {
    $m = new MongoClient();
    $db = $m->selectDB("Laravel");      
    $collection = $db->selectCollection("Posts");
    $document = array( 
       "Title" => $request->input('Title'), 
       "Publisher" => $request->input('Publisher')
    );      
    $collection->insert($document);
}    

But when I click "Submit", it gives me an error :

Fatal error: Class 'App\Http\Controllers\MongoClient' not found

I have run MongoDB Server and also Wamp and I have installed MongoDB and it's driver for PHP …

What is my mistake ? (I should say that I haven't done any config for Laravel by using MongoDB. Is it needed ?)

12
  • 1
    Try new \MongoClient() instead Commented Aug 5, 2016 at 13:25
  • @apokryfos Thanks but It showed this : Fatal error: Class 'MongoClient' not found Commented Aug 5, 2016 at 13:27
  • Did you install the MogoClient or the MongoDB client? Commented Aug 5, 2016 at 13:29
  • @apokryfos I have installed MongoDB 3.2 & It's driver but I haven't installed the MongoClient ..., Indeed I haven't done any CONFIG for laravel, Is it needed ? Commented Aug 5, 2016 at 13:33
  • You said you installed its driver for PHP, I've given you links to 2 different clients for PHP, you need to check which one you've installed because they use different class names. Unless you've installed another one. Commented Aug 5, 2016 at 13:34

1 Answer 1

3

Laravel doesn't come with a driver for MongoDB.

If you want to use mongo with laravel you'll have to create your own class to deal with it or use this one:

laravel-mongodb

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks My Friend but I don't want to use package, I'm beginner I prefer to use it regularly ...
I'm not following your logic. If you're a beginner, wouldn't it follow that you would want to use a pre-built package specific to the framework you're using instead of rolling your own implementation?
Rolling my own implementation is better than a package, Especially for me that I want to understand more the MongoDB Syntax ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.