The issue with the provided code is that the SUM function is not being used correctly with the WHERE clause. Instead of using AND inside the SUM function, the WHERE clause should be added separately. Here's an updated version of the code:
$query = DB::table('cash_table')
->where('transaction_created', '>=', Carbon::now()->startOfWeek())
->select(DB::raw('
SUM(amount) as transaction_amount,
COUNT(amount) as transaction_count,
SUM(CASE WHEN type = "dispute" THEN amount ELSE 0 END) as charge_amount,
COUNT(CASE WHEN type = "dispute" THEN amount ELSE NULL END) as charge_count,
SUM(CASE WHEN type = "loan" THEN loan_amount ELSE 0 END) as loan_amount,
COUNT(CASE WHEN type = "loan" THEN loan_amount ELSE NULL END) as loan_count
'))
->groupBy('transaction_created')
->get();
In this updated code, the SUM function is used with a CASE statement inside it to filter the rows based on the type column. The COUNT function is also updated to use CASE statement to count only the rows that match the type condition.