Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lewanay's avatar

Laravel date error

I am using query builder to fetch some data but for the created_at date I am using Carbon::parse(), but it's giving me error something like this:

DateTime::__construct(): Failed to parse time string

Can someone tell me what's wrong with this?

My query:

Carbon::parse(DB::table('students_attendances') ->join('students_classes', 'students_attendances.class_id', '=', 'students_classes.id') ->select('students_attendances.id', 'students_classes.class_name', 'students_attendances.created_at') ->orderBy('id', 'asc')->get())->toCookieString();

0 likes
7 replies
wilburpowery's avatar

You need to only pass the actual created_at value to Carbon::parse(). Right now from what I can see you're passing a collection since ->get() returns a collection.

Snapey's avatar

Parse is for a single date string

Its not going to work if you give it a whole collection of rows, especially when each row contains

select('students_attendances.id', 'students_classes.class_name', 'students_attendances.created_at')

Not sure what you were thinking it would do?

lewanay's avatar

@SNAPEY - So what if i want to parse the collection ? Or any other method for this ?

munazzil's avatar

If you want a collection then simply use ->toArray() method.

Snapey's avatar

So what if i want to parse the collection ?

Parse it how? Do you know what Carbon is?

1 like
rawilk's avatar

@munazzil Seriously? toArray() gives you an array, not a collection. I mean it's even in the name... And also, Carbon is not a collection, so it won't have that method anyways.

Cronix's avatar

Try using Eloquent models instead of the query builder. All created_at/updated_at timestamps are automatically converted to carbon instances when you retrieve them from the db. There is no need to manually parse them. It also makes it very easy to add other custom date/datetime columns that you may have in a table so they are automatically converted to carbon instances as well. Eloquent is a lot more powerful than the simple, basic query builder that you are using.

https://laravel.com/docs/5.8/eloquent-mutators#date-mutators

1 like

Please or to participate in this conversation.