Home > Database > Mysql Tutorial > How Can I Group Laravel Eloquent Results by Days?

How Can I Group Laravel Eloquent Results by Days?

Patricia Arquette
Release: 2024-11-03 15:09:03
Original
647 people have browsed it

How Can I Group Laravel Eloquent Results by Days?

Grouping Laravel Eloquent Results by Days

When working with a table containing records that track user activity, grouping by days can be useful for obtaining insights into traffic patterns. However, the presence of different times for each record can hinder accurate grouping.

Solution 1: DB::Raw Query

To achieve day-based grouping, utilize the DATE() function in MySQL. This function strips away time components from timestamps, resulting in pure dates.

DB::table('page_views')
    ->select(DB::raw('DATE(created_at) as date'), DB::raw('count(*) as views'))
    ->groupBy('date')
    ->get();
Copy after login

Solution 2: Eloquent Query with Carbon

To remain within the Laravel Eloquent framework, leverage Carbon for date manipulation. The first where clause filters records created within the last month. Grouping by date and ordering by it in descending order ensures chronological presentation.

<code class="php">$visitorTraffic = PageView::where('created_at', '>=', \Carbon\Carbon::now()->subMonth())
                            ->groupBy('date')
                            ->orderBy('date', 'DESC')
                            ->get(array(
                                DB::raw('Date(created_at) as date'),
                                DB::raw('COUNT(*) as "views"')
                            ));</code>
Copy after login

The above is the detailed content of How Can I Group Laravel Eloquent Results by Days?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template