Search code examples
laraveleloquentlaravel-query-builder

Laravel groupBy with select multiple field


I can select country and groupBy the result as following with an alias total :

Data::select('country', DB::raw('count(*) as total'))
->groupBy('country')
->get();

The above code works well. Here I can select only country filed, But I need to select aslo name, positions field, How can I select multiple field here?


Solution

  • You have to use like below settings and change code.

    1. Open config/database.php
    2. Find strict key inside mysql connection settings
    3. Set the value to false

    Use code below like

    ModelName::groupBy('country')
    ->selectRaw('count(*) as total, country, name, positions')
    ->get()