I am using Laravel Model collection and want to filter the records in the first statement, I am checking that I only check the ends when it's has some date otherwise doesn't compare the value. How to check the null value in this collection?
2nd if is working properly. I also used the filter method but it's not working for me. Can anyone suggest to me how to do this in a proper laravel way? I know I can do this using for each loop but I want to make the query faster. Please suggest your answers. Thank you
$subscriptionsCount = Subscription::where( function($query) {
if($query->where('ends_at', '!=' , null)){
$query->where('ends_at', '>=', now());
}
else if($query->where('subscription_ends_at', '>=', now())){
$query->where('subscription_ends_at', '>=', now());
}
})->where('name', $betTypeName)->count();
CodePudding user response:
Can you try this code as I understood from your question you need whereNotNull
$subscriptionsCount = Subscription::where(function ($query) {
$query->whereNotNull('ends_at')->where('ends_at', '>=', now());
})->where(function ($query) {
$query->whereNotNull('subscription_ends_at')->where('subscription_ends_at', '>=', now());;
})->where('name', $betTypeName)->count();
CodePudding user response:
You can try with below whereRaw condition :
$subscriptionsCount = Subscription::where( function($query) {
$query->whereRaw("(CASE WHEN ends_at is not null THEN ends_at = now() WHEN subscription_ends_at >= now() THEN subscription_ends_at >= now() END)" );
})->where('name', $betTypeName)->count();
Hope Above code will be help you. Code is not tested but logic will help you. :)