PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, December 30, 2021

[FIXED] How to connect cakephp 4.x to mongodb?

 December 30, 2021     cakephp, mongodb     No comments   

Issue

How can I connect cakephp version 4.x to mongoDB. I tried many ways but couldn't. I need help from the community. Thanks


Solution

You can follow below steps

  1. Install the library by running:

    composer require mongodb/mongodb
    
    
  2. You can create a folder in your src folder

    Example you location is : app/cake/src/Mongo/connection.php

  3. Then you can write below code to connect mongo

    <?php 
    
    namespace App\Mongo;
    use MongoDB\Client as Mongo;
    
    class Mongo {
    
    public function connection(){
       $user = "admin";
       $pwd = 'password';
    
       return new Mongo("mongodb://${user}:${pwd}@127.0.0.1:27017");
    
    '''
    }
    
    
  4. Use this class in any controller

    <?php 
        use App\Mongo\Mongo;
        //In before filter method 
        $this->mongo = new Mongo;
        '''''



Answered By - Alimon Karim
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing