0

Is there any chance to use Illuminate Query builder to get dates as Carbon objects instead of strings?

For example:

$user=DB::table('users')->select(["id","lastLogin"])->where("id",1)->first();

$user->lastLogin; // <--- Carbon instead of string!
Tobia
  • 9,165
  • 28
  • 114
  • 219

1 Answers1

0

You can use Carbon::parse($user->lastLogin), but I think there is no native way to get dates as carbon objects without using eloquent. An example is this answer on stackoverflow.

I think working with eloquent models will make the work much easier. So you can set the $dates property to get the lastLogin as carbon object. More informations at laravel docs.

UfguFugullu
  • 2,107
  • 13
  • 18
  • I agree, the point is in my application I use few models (like my example) and many joined queries. This is why I'm looking to understand if is there any way to map types in query builder response. – Tobia Apr 21 '20 at 13:20
  • If there is a possibility, I would also find it quite interesting. Could you handle the joined tables as models too? – UfguFugullu Apr 21 '20 at 13:23
  • Maybe, but then should I define a model for each query response? I found easier and faster using querybuilder in my case. – Tobia Apr 21 '20 at 13:26
  • Not for every result of the query, more or less for every significant table (for example: users, posts, comments). Does this help you? – UfguFugullu Apr 21 '20 at 13:48
  • If I have a query with userId and number of posts, I have to create a specific model for this. After, if I need a query with posts with its comments count, i need another model... am I wrong? – Tobia Apr 21 '20 at 16:04
  • @Tobia In this example you do only need the models "user", "post" and "comment". Further you can declare any relation of the models like descriped in the laravel docs: https://laravel.com/docs/7.x/eloquent-relationships#defining-relationships After that you can implement the counting of related models: https://laravel.com/docs/7.x/eloquent-relationships#counting-related-models – UfguFugullu Apr 22 '20 at 05:42