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

krunal05's avatar

eloquent query by date

Here is the image:

https://imgur.com/Uya8P70

Basically, let's say, I have created:
2 posts on 1 Feb, 
4 posts on 2 Feb,
None on 3 Feb,
3 posts on 4 Feb,
and so on...

I want to get query in array something like:

[
[2022-02-01] => [
                          ["id" =>1, "title" => "Post 1" ],
						  ["id" =>2, "title" => "Post 2" ]
],
[2022-02-02] => [
                          ["id" =>3, "title" => "Post 3" ],
						  ["id" =>4, "title" => "Post 4" ],
							["id" =>5, "title" => "Post 5" ],
						  ["id" =>6, "title" => "Post 6" ],
],
[2022-02-04] => [
                          ["id" =>7, "title" => "Post 7" ],
						  ["id" =>8, "title" => "Post 8" ],
							["id" =>9, "title" => "Post 9" ],
],
]
```````````
0 likes
4 replies
Nakov's avatar

And what have you tried ?

$posts = Post::groupBy('created_at')->get();
krunal05's avatar

@Nakov Hello nakov thanks for the reply. I throws error

$forms_submitted = FormSubmission::with('form')
                            ->where('account_id',$user_id)
                            ->groupBy('created_at')
                            ->get();

SQLSTATE[42000]: Syntax error or access violation: 1055 'form_submissions.id' isn't in groupby (SQL: select * from 'form_submissions` where `account_id` = 1 group by 'created_at')

'form_submissions' is my table name

tjanuki's avatar
tjanuki
Best Answer
Level 42

How about this one? You can group the results using collection methods.

    $results = FormSubmission::with('form')
        ->select([DB::raw('DATE(created_at) as date'), 'form_submissions.*'])
        ->where('account_id', $user_id)
        ->get()
        ->groupBy('date')
        ->toArray();

https://laravel.com/docs/master/collections#method-groupby

1 like

Please or to participate in this conversation.