Search code examples
phplaravelphp-carbon

Getting an element from Carbon class object


In Laravel, when I was trying to print the value from the column created_at", I discovered that the value from this column is sent from the database as an instance of the class - Illuminate\Support\Carbon. After that, I am trying to print each element of this object, for example:

{
  "date":"2018-09-12 11:00:00.000000",
  "timezone_type":3,
  "timezone":"UTC"
}

I want to print "date". When I write the following:

$user = User::get(); // everything for every user
$first = $user[0]; // first user
$created = $user[0]['created_at']; // object of this Carbon class
$date = $created[0]; // or $created['date'])` date specifically

An error occurs:

Cannot use object of type Illuminate\Support\Carbon as array.

I can not find the reason for this. Any solution?


Solution

  • Laravel converts anything declared as a date into a Carbon object when it retrieves the model. You're attempting to use Array syntax on an Object.

    Try $user->created_at or $user->created_at->format('m/d/Y')

    You may also benefit from learning about Arrays and Objects and their differences in PHP.