Aggregate and count data by date in Laravel and PostgreSQL

I recently migrated from MySQL to Postgres and I haven't been able to translate this MySQL query to a Postgres one:

function aggregate($query, $table, string $order): array
{
    $by = $order === 'day' ? 'date' : 'month';

    $from = $by === 'date' ? now()->subDays(14) : now()->subYears(2);

    $dateKey = $by === 'date' ? "DATE($table.created_at)" : "EXTRACT(YEAR_MONTH from $table.created_at)";
    $aggregate = $query->select([
        DB::raw("$dateKey as `{$by}`"),
            DB::raw("COUNT($table.id) as `count`"),
        ])
        ->whereBetween("$table.created_at", [$from, now()])
        ->groupBy($by)
        ->orderBy($by)
        ->get()->toArray();

    return $this->formatAggregates($aggregate, $by);
}

That works when the DB was MySQL but fails on Postgres. This query returns an array of associatives like date=>2021-01-23, count=>4 where the date is a day of the year (yyyy-mm-dd) or a month (yyyy-mm), and the count is the aggregate of all the times that date is repeated.

This is as far as I've gotten as of yet:

    $by = $order === 'day' ? 'date' : 'month';
    $from = $by === 'date' ? now()->subDays(14) : now()->subYears(2);

    $dateKey = $by === 'date' ? "DATE('day', $table.created_at)" : "DATE_TRUNC('month', $table.created_at)";
    $aggregate = $query->select([
        DB::raw("$dateKey AS date"),
        DB::raw("COUNT($table.created_at) AS count"),
    ])->groupBy('date')->orderBy('date')->get();
    dd($aggregate);

I haven't even included the condition to look only for either the last 2 weeks or the last 2 years. I'm ok with it returning a truncated timestamp instead of the yyyy-mm-dd / yyyy-mm formats for day / month.

The error I'm getting from this is that Postgres required me to either group_by or aggregate something coming from the $query argument (codes.business_id). Which, for context, is something like this in Laravel:

$query = $this->hasManyThrough(Scan::class, Code::class, 'business_id', 'code_id');

It's a long shot, but I'd greatly appreciate anyone who can help me make that query work in Postgres...