Home > Mobile >  How to distinguish two objects Carbon\Carbon and Illuminate\Support\Carbon when getting mongoDB d
How to distinguish two objects Carbon\Carbon and Illuminate\Support\Carbon when getting mongoDB d

Time:08-13

I have a question, but can't find an answer. So now I ask everyone to answer for me. If the question is not reasonable, please forgive me.

I am doing MongoBD with Laravel. My updatedAt field is saved as timestamp 1606789482 type (int 32), and when I retrieve the data it will be as object(Illuminate\Support\Carbon) :

public function update(Request $request)
{
    $prodcut = Product::where('_id', '=', $request->data['_id'])->first()->toArray();
    dd($prodcut['updatedAt']);
    // result:
    //object(Illuminate\Support\Carbon)#1433 (3) {
     //["date"]=>
     //string(26) "2022-08-10 15:30:33.000000"
     //["timezone_type"]=>
     //int(3)
     //["timezone"]=>
     //string(3) "UTC"
    //}
}

But for some reason some of my productions save updatedAt as ISODate("2013-10-01T00:00:00.000Z") type (date). And when I get updatedAt it looks like this:

object(Carbon\Carbon)#1377 (3) {
  ["date"]=>
  string(26) "2013-10-01 00:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}

Is there a way to distinguish between object(Illuminate\Support\Carbon) and object(Carbon\Carbon) ?

Because when updating most successfully, But some products with updatedAt with type date got an error: Object of class Carbon\\Carbon could not be converted to int !

So I want to check if it is date ISODate then I will remove updatedAt before updating. Please give me your opinion. Thanks.

CodePudding user response:

You can try something like this:

    public function isIlluminateCarbon($param): bool
    {
        return (bool) ($param instanceof \Illuminate\Support\Carbon);
    }

    public function isCarbonCarbon($param): bool
    {
        return (bool) ($param instanceof \Carbon\Carbon);
    }

    // Call methods

    if ($this->isIlluminateCarbon($values)) {
        // is \Illuminate\Support\Carbon
    }

    if ($this->isCarbonCarbon($values)) {
        // is \Carbon\Carbon
    }
  • Related