Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

pifou's avatar
Level 1

Eloquent standalone, unable to query with count and groupBy

Hello, I'm new with eloquent, working as it, standalone :) it works pretty good with simple query, but I'm unable to make just a count(*) with groupBy... Here is the code:

class Btc extends Illuminate\Database\Eloquent\Model {
    static function getNb(int $mid, array $btc = [], array $etat = []) {
        $req = Btc::select('btc_mid', 'btc_type', Btc::raw('COUNT(*) as btc_nb'))->where('btc_mid', '=', $mid);
        if(!empty($btc))
            $req->whereIn('btc_id', $btc);
        if(!empty($etat))
            $req->whereIn('btc_etat', $etat);
        echo $req->toSql();
        // indexer le resultat sur btc_type
        return index_array($req->groupBy('btc_mid', 'btc_type')->get(), 'btc_type');
    }
}

and the error: Warning : strtolower() expects parameter 1 to be string, object given URL: /gen.html File: Grammar[058] the 'toSql' I added show me the trouble: the request is not complete, missing the predicate count(*) but I can't undersand where i'm wrong? select btc_mid, btc_type, from zrd_btc where btc_mid = ? and btc_etat in (?)

0 likes
3 replies
pifou's avatar
Level 1

Thanks for your answer; I don't have DB variable as I run eloquent as a standalone framework (Fatal error: Uncaught Error: Class 'DB' not found ...) but I did it with my own Manager instance :

$_sql2 = new Illuminate\Database\Capsule\Manager();
...
class Btc extends Illuminate\Database\Eloquent\Model {
    static function getNb(int $mid, array $btc = [], array $etat = []) {
        global $_sql2;
        $predicate = $_sql2::raw('COUNT(btc_id) as btc_nb');
        $req = Btc::select('btc_mid', 'btc_type', $predicate)->where('btc_mid', '=', $mid);
        if(!empty($btc))
            $req->whereIn('btc_id', $btc);
        if(!empty($etat))
            $req->whereIn('btc_etat', $etat);
        // indexer le resultat sur btc_type
        $result = $req->groupBy(['btc_mid', 'btc_type'])->get();
        return index_array($result, 'btc_type');
    }
}

I don't know how to do it without the 'global' variable instance of Manager() and even if it is possible? Anyway, it works as it :)

(edit) I did it by defining my own DB class as it, it was really simple !

class DB extends Illuminate\Database\Capsule\Manager{}

DirkZz's avatar

Your future you or fellow programmers working on the project will thank you if you get rid of the global now.

Bobby was right but you had this error; Fatal error: Uncaught Error: Class 'DB' not found because you didnt reference it by the full namespace, or including it at the top with the use statement.

If you use PHPStorm you can let it autocomplete it for you with Alt + Enter.

Please or to participate in this conversation.