phplaravelmongodbjenssegers-mongodb

MongoDB Laravel Jenssegers package: Undefined class constant 'PRIMARY' when inserting into DB


We are using Laravel 8.0, MongoDB 5.0 with driver version 1.16 and the Jenssegers package 3.8 which seem compatible together according to the manual presented in the following:

https://github.com/jenssegers/laravel-mongod

Our MongoDB configuration is as follows:

'mongodb' => [
   'driver'   => 'mongodb',
   'host'     => env('DB_CONNECTION_THIRD', 'localhost'),
   'port'     => env('DB_PORT_THIRD', 27017),
   'database' => env('DB_DATABASE_THIRD', 'your_db_name'),
            'username' => env('DB_USERNAME_THIRD', 'your_username'),
   'password' => env('DB_PASSWORD_THIRD', 'your_password'),
],

Also, the sample model is something like this:

namespace App\Models\AI;

use Jenssegers\Mongodb\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Chatgpt extends Model
{
    protected $connection = 'mongodb';
    protected $collection = 'my_log';
}

Every time we try to insert a record to the database, we got the same error:

"message": "Undefined class constant 'PRIMARY'"

Even, we tried with defining primary key but it did not work. We tried different solutions but the issue is still alive. Nothing certain is discussed about this issue in the community. Any help or clue is appreciated.


Solution

  • The following code is the default template for defining the read preferences located in mongodb/mongodb/src/function.php:

     $readPreference = extract_read_preference_from_options($options);
        if (! $readPreference instanceof ReadPreference) {
            // TODO: PHPLIB-476: Read transaction read preference once PHPC-1439 is implemented
            $readPreference = new ReadPreference(ReadPreference::PRIMARY);
        }
    

    We should have altered it by the following changes:

    $readPreference = new ReadPreference('primary');
    

    I already checked this solution and it works!