Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fatal error: Class 'MongoDate' not found when using mongodb php driver 1.1.2 and PHP 7.0.2 - Laravel 5.1

I am trying to configure MongoDB to work with my Laravel 5.1 Homestead instance on a virtual Ubuntu 14.04 machine. I was able to successfully install the latest version of MongoDB which supports PHP 7.0 using sudo pecl install mongodb (this is correct for 7.0, not sudo pecl install mongo anymore).

I then added the extension in my php.ini files (all three) on my Ubuntu machine, each in:

  • /etc/php/7.0/cli/php.ini
  • /etc/php/7.0/fpm/php.ini
  • /etc/php/7.0/cgi/php.ini

This is the extension I wrote which is correct for use with PHP 7.0:

  • extension=mongodb.so (not mongo.so anymore)

When I run phpinfo() in my browser, it states that MongoDB is properly configured with my PHP 7.0.

If MongoDB is properly configured, how come I keep getting:

Fatal error: Class 'MongoDate' not found

when I try to run my migrations and seeds with php artisan migrate:refresh --seed?

I already tried:

  • rebooting the Ubuntu machine with vagrant reload and vagrant reload --provision
  • Restarting PHP and Nginx with sudo service nginx restart and sudo service php7.0-fpm restart

Neither have worked.

like image 683
Graham S. Avatar asked Jan 08 '16 00:01

Graham S.


2 Answers

As you mentioned you're using the new Mongo extension for PHP 7.

The class names have changed from the older version, i.e.

MongoClient is now MongoDB\Driver\Manager

MongoDate is now MongoDB\BSON\UTCDateTime

I'm not sure how backwards compatible everything is, but this should get you started!

like image 72
morrislaptop Avatar answered Nov 19 '22 09:11

morrislaptop


Throughout our app we were regularly converting unix timestamps into MongoDate instances. Example:

new MongoDate(strtotime('-1 day'));

I've therefore created a class to allow conversion between unix timestamps and the new MongoDB\BSON\UTCDateTime, and back

<?php

class MongoHelper {

    const SECONDS_IN_A_MILLISECOND = 1000;

    public static function getMongoUTCDateTimeFromUnixTimestamp($timestamp) {
        return new \MongoDB\BSON\UTCDateTime(intval($timestamp * self::SECONDS_IN_A_MILLISECOND));
    }

    public static function getUnixTimestampFromMongoUTCDateTime(\MongoDB\BSON\UTCDateTime $utc_date_time) {
        return intval((string) $utc_date_time / self::SECONDS_IN_A_MILLISECOND);
    }
}

Example usage:

MongoHelper::getMongoUTCDateTimeFromUnixTimestamp(strtotime('-1 day'));
like image 33
Jon M Avatar answered Nov 19 '22 09:11

Jon M