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:
vagrant reload
and vagrant reload --provision
sudo service nginx restart
and sudo service php7.0-fpm restart
Neither have worked.
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!
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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With