Eloquent : Count of posts for a period with one row per day
Hi,
I need to create a graph for the last 30 days, so I need the count of post created per day. Right now I'm having this :
$chartDatas = Post::select([
DB::raw('DATE(created_at) AS date'),
DB::raw('COUNT(id) AS count'),
])
->whereBetween('created_at', [Carbon::now()->subDays(30), Carbon::now()])
->groupBy('date')
->orderBy('date', 'ASC')
->get()
->toArray();
This is working but I just have the count for days that actualy have a post created. I need to have 0 for the days that doesn't have a post. So I should have 30 rows for each query as I need the last 30 days, and have 0 on the count column when no post exists on that day.
You can create a custom collection for your model. Then you can implements a method that return a subcollection for a day by using the filter method.
use Illuminate\Support\Collection;
class PostCollection extends Collection{
function filterDay($day)
{
return $this->filter(function($post){
// Check whether the post is from this day
return $is_from_this_day;
}
}
}
class Post extends Eloquent{
public function newCollection($posts)
{
return new PostCollection($posts);
}
}
then in your view
@foreach($last_30_days as $day)
<?php $posts_from_this_day = $posts->fromDay($day) ?>
<h2>{{ count($posts_from_this_day }}) posts from the day {{ $day }}</h2>
<ul>
@foreach($posts_from_this_day as $post)
<li>{{ $post->title }}</li>
@endforeach
</ul>
@endforeach
Thank you @Mushr00m four your reply :
That's what i get with DB::raw('MONTH(created_at) AS month')
SQLSTATE[42883]: Undefined function: 7 ERROR: function month(timestamp without time zone) does not exist LINE 1: select MONTH(create_at) AS month, COUNT(*) AS count from "vi... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. (SQL: select MONTH(create_at) AS month, COUNT(*) AS count from "view_resacashin" where "create_at" between 2014-05-16 and 2014-10-16 group by "month" order by "month" asc)
Ho yes, I think you have a typo, it should be "created_at" and not "create_at". And of course you must not have public $timestamps = false; in your model.
Looking at your error, the "create_at" is not recognise as a datetime column so Month can't work. You have to fix that part. I've never used Postgres so I can't help you much.
Hello. I tried to use the solution from @thepsion5 but I'm really not experienced to Laravel and maybe because of this I'm not getting success to my task.
I need to create a graph from the last 7 days. The first part ("$chartDatas = /** your previous code */;") worked fine, but the second I can't understand how to do.
This entire code is uploaded to the Controller? Thanks.