Search code examples
phpjsonlaravelcontroller

count json array controller laravel


I am learning JSON and I want to show a custom output. The dates are the same, they must be added together.

The data of my database table is as follows:

id  no_id   type     created_at
------------------------------------------------
1    1      post     2023-10-11T17:13:19.000000Z
2    85     post     2023-10-11T17:13:19.000000Z
3    23     post     2023-10-12T17:24:33.000000Z
4    40     post     2023-10-12T17:24:33.000000Z
5    87     product  2023-10-12T17:24:33.000000Z

Example:

2023-10-11 => 2
2023-10-12 => 3

My Laravel's controller file is as follows:

class StatController extends Controller {
    public function index() {
        $stats = Stat::groupBy(DB::raw('DATE(created_at)'))->get()->toArray();

        return array_reverse($stats);
    }
}

The output of the controller code shows as follows (json):

[
    {
        "id": 2,
        "no_id": 85,
        "type": "post",
        "created_at": "2023-10-11T17:13:19.000000Z"
    },
    {
        "id": 5,
        "no_id": 87,
        "type": "product",
        "created_at": "2023-10-12T17:24:33.000000Z"
    }
]

But I want to show the JSON output as follows:

[
    {
        "date": "2023-10-11",
        "totalViews": "2"
    },
    {
        "date": "2023-10-12",
        "totalViews": "3"
    }
]

Solution

  • You can try groupBy created_at and count each group like this:

    $stats = Stat::selectRaw('DATE_FORMAT(created_at,"%Y-%m-%d") as date, COUNT(*) as totalViews')
       ->groupBy(DB::raw('DATE(created_at)'))
       ->get()
       ->toArray();