Laravel-mongodb: How to convert dates to ISODate

Created on 14 Sep 2016  路  3Comments  路  Source: jenssegers/laravel-mongodb

Hi guys,

I'm using Laravel 5.2 (PHP 5.6.25 (Mac OS) and the lib is not converting Carbon dates (like Carbon::now(), or something like DateTime(xxxx)) to native ISODate format. For example, when I run Log::where('created_at', '<=', Carbon::now())->get(); it makes the query like {"created_at":{"$lte":{}}}]}. It works perfectly without dates!

It's my model:

``` namespace App\Models;

use Jenssegers\Mongodb\Eloquent\Model;

class Log extends Model
{

protected $connection = 'mongodb';
protected $table = 'log';
protected $dates = ['created_at'];

}

```

My php -i | grep -i mongodbresult:
mongodb
mongodb support => enabled
mongodb version => 1.1.8
mongodb stability => stable
libmongoc version => 1.3.5
mongodb.debug => no value => no value

Most helpful comment

Try this way, use "\MongoDB\BSON\UTCDateTime" because "MongoDate" id deprecated and "DateTime" will convert your date to timestamp in milliseconds.

$date = new \MongoDB\BSON\UTCDateTime(new DateTime("2017-03-31");

All 3 comments

It is a bug when you are using whereBetween, te class Builder doens't check the $where['values'] array to convert DateTime objects to MongoDB\BSON\UTCDateTime. I did the changes and opened a PR #953.

Try this way, use "\MongoDB\BSON\UTCDateTime" because "MongoDate" id deprecated and "DateTime" will convert your date to timestamp in milliseconds.

$date = new \MongoDB\BSON\UTCDateTime(new DateTime("2017-03-31");

Is it possible to use the MongoDate in the following way?
use MongoDB\BSON\UTCDateTime as MongoDate;

$start = new MongoDate(strtotime($request->year . '-' . $request->month . '-01 00:00:00'));
$end = new MongoDate(strtotime($request->year . '-' . $request->month . '-31 00:00:00'));
$query->whereBetween('created_at', array($start, $end));
I tried but got a null array.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

geofflancaster picture geofflancaster  路  3Comments

imrannazirbhat picture imrannazirbhat  路  3Comments

phuocduy1988 picture phuocduy1988  路  3Comments

viacheslavpleshkov picture viacheslavpleshkov  路  3Comments

sanjay1688 picture sanjay1688  路  3Comments