Gireesh Gireesh - 7 months ago 226
PHP Question

ErrorException in Model.php preg_match() expects parameter 2 to be string, array given in Laravel 5.2

I am using jenssegers mongodb
I am trying to save created_at and updated_at in my controller, while inserting some data in mongodb

'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),


I have included
use Carbon\Carbon;
on the top of the controller

and the dates are inserting the db as

"updated_at" : ISODate("1970-01-11T19:45:21.925Z"),
"created_at" : ISODate("1970-01-11T19:45:21.925Z")


This is one issue, the dates are
1970, not 2016


while trying to update the table, I am using
'updated_at' => Carbon::now(),


after that it is saved as object in db like this

"updated_at" : {
"date" : "2016-04-22 11:34:44",
"timezone_type" : 3,
"timezone" : "UTC"
},


and after that, if I try to get that particular row, I am getting this error

ErrorException in Model.php line 2951:
preg_match() expects parameter 2 to be string, array given

in Model.php line 2951
at HandleExceptions->handleError('2', 'preg_match() expects parameter 2 to be string, array given', 'C:\wamp\www\tasker\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php', '2951', array('value' => array('date' => '2016-04-22 11:34:44', 'timezone_type' => '3', 'timezone' => 'UTC')))
at preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})$/', array('date' => '2016-04-22 11:34:44', 'timezone_type' => '3', 'timezone' => 'UTC')) in Model.php line 2951


Please help me.
Thanks in advance!

Answer

Actually - when using jenssegers/Laravel-MongoDB package - created_at and updated_at attributes are automatically set when saving a new model object.

However if you still want manually set timestamps or anything else datetime field you MUST convert a DateTime object (or Carbon) to MongoDB\BSON\UTCDateTime.

So it would be something like this:

$myModel = new MyModel();
$myModel->created_at = $myModel->fromDateTime(new \DateTime());
//...

And for another datetime attribute other than created_at/updated_at:

class Task extends Model
{
    protected  $collection = 'tasks';

    protected $duedate;

    protected  $dates = ['duedate'];

    /** Mutator */
    public function setDuedateAttribute($value)
    {
        /** @var \MongoDB\BSON\UTCDateTime */
        $this->attributes['duedate'] = $this->fromDateTime(
            \DateTime::createFromFormat('d/m/Y H:i', $value . '00:00'));
    }
}

Jenssegers\Mongodb\Eloquent::fromDateTime() is available from any model instance as it inherits from parent model (see in github). This method convert a DateTime to a storable UTCDateTime object (which is the internal datetime mongo rep).