'Create variable based query to select data in laravel

I created a helper function for count all notification in navbar, For this I am storing clause in a single variable.

I am accessing it by calling-

countData("notification","WHERE seen_status = '0'") 

My function is-

function countData($table,$clause) {
    $result = DB::select("SELECT * FROM $table $clause");
    return count($result);
}

It working fine, but getting error in-

countData("projects","GROUP BY user")

I can use groupBy('user') but problem is, I don't want to pass too many variable inside my function. So, is there any option to run my custom query by using single variable?



Solution 1:[1]

The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more columns.

So the problem here is that you need to use an aggregate function first then group it

Solution 2:[2]

I think your group by must have a specific column in your select.

try that


function countData($columns,$table,$clause) {
    $result = DB::select("SELECT $columns FROM $table $clause");
    return count($result);
}

countData("user","projects","GROUP BY user")

or you can simply make one variable for all your selects

function countData($query) { $result = DB::select($query); return count($result); } 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joseph
Solution 2 MelB