Laravel group by if column value exits then group by perform other wise as it is return records in single laravel query
i have tried this
$sql = $this->expense->builder()->where('session_year_id',1)->whereNull('staff_id')->orWhereNotNull(function($q){
$q->groupBy('month');
})->get();
2
Answers
It seems like you want to perform a conditional GROUP BY in Laravel based on whether a certain column value exists or not. The query you’ve posted has some issues, but I’ll help you correct it. You can achieve this using conditional logic and the groupBy method.
Assuming you want to group by the ‘month’ column if there are any non-null values in that column, and if all values are null, you want to return all records without grouping, you can do the following:
In this code:
This way, the grouping will only occur when there are non-null values in the ‘month’ column, and you get all records as they are when all values in ‘month’ are null.
To achieve the desired result of returning both grouped by month and separate records when there are null values in the ‘month’ column, you can use a combination of GROUP BY and a union query. Here’s how you can do it in Laravel:
In this code:
This approach will give you both grouped records based on ‘month’ and separate records when ‘month’ is null.