it is possible to write something like that ?
$date = '2021-05-01';
$users = User::
select( [
DB::raw('(SELECT COUNT(*) FROM bookings WHERE bookings.user_id = users.id
if($date != null){
WHERE bookings.date = $date
}
) as count')
] );
You could construct sql outside the raw function, something like this
$sql = '(SELECT COUNT(*) FROM bookings WHERE bookings.user_id = users.id ';
if($date != null){
$sql .= "WHERE bookings.date = $date";
}
but with proper relationships between User and Booking Models you could end up with a clenear code
use eloquent?
$bookings = User::bookings()->whereDate('date', $date)->count();
Please or to participate in this conversation.