Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a user with highest post created in last 24 hours, laravel Eloquent

How to find the user with the highest post created in the last 24 hours in laravel? sorted by the number of posts in descending order.

like image 893
Nicholas Francis Avatar asked Mar 06 '23 02:03

Nicholas Francis


2 Answers

If I'm not wrong, you are asking for the users with the highest number of posts created in the last 24 hrs.

To accomplish this, do the following:

$users = User::withCount(['posts' => function ($query) {
            $query->where('created_at', '>=', carbon()->now()->subDay());
        }])->orderBy('posts_count', 'DESC')
            ->get();

As the documentation states, you can add constraints to the queries.

Counting Related Models

If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models. For example:

$posts = App\Post::withCount('comments')->get();

foreach ($posts as $post) {
    echo $post->comments_count;
}

You may add the "counts" for multiple relations as well as add constraints to the queries:

$posts = Post::withCount(['votes', 'comments' => function ($query) {
    $query->where('content', 'like', 'foo%');
}])->get();

echo $posts[0]->votes_count;
echo $posts[0]->comments_count;
like image 81
Kenny Horna Avatar answered Apr 28 '23 07:04

Kenny Horna


use Carbon\Carbon;

get user id:

 $minusday = Carbon::now()->subDay();
 $user_id = DB::table('posts')
            ->select('user_id', DB::raw('count(id) as total'))
            ->where('created_at', '>=', $minusday)
            ->groupBy('user_id')
            ->orderBy('total','desc')
            ->limit(1)
            ->get();
like image 41
Manpreet Avatar answered Apr 28 '23 09:04

Manpreet