Home > Mobile >  how to count repetitive registers in a column mysql laravel
how to count repetitive registers in a column mysql laravel

Time:07-22

im new in Laravel and i want to count repetitive registers in a field name "career" from a table named "students"

Table students

career
-------
1
1
2
1

desired output 
---------------

3
1

indicating "three" repetitive ones (1) and "one" number (2)

i am using $results = DB::select('select * from students', array(1)); to read career field with the output 1121 how can i do in order to count repetitive registers ? anyhelp is appreciated

CodePudding user response:

Here is the raw MySQL query you want:

SELECT COUNT(*) AS cnt
FROM students
GROUP BY career
ORDER BY career;

It should be straightforward to figure out how to port the above to Laravel code.

CodePudding user response:

 $results = DB::table("students")
            ->select("count (*) as cnt")
            ->where(DB::raw("career"))
            ->groupBy("career")
            ->get();

CodePudding user response:

you need to count all records by grouping the career field, this is more related to mysql here is the fiddle for mysql enter image description here for Laravel you can run the following query,

$career = DB::table('students')
                 ->select('career', DB::raw('count(*) as registers'))
                 ->groupBy('career')
                 ->get();
  • Related