Search code examples
laraveleloquentmethod-chaininglaravel-collection

Apply conditions using closure on Laravel Model collection


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();

Solution

  • Can you try this code as I understood from your question you need whereNotNull

         $subscriptionsCount = Subscription::where(function ($query) {
            $query->where(function ($query) {
                $query->whereNotNull('ends_at')->where('ends_at', '>=', now());
            })->orWhere(function ($query) {
                $query->whereNotNull('subscription_ends_at')
                      ->where('subscription_ends_at', '>=', now());
            });
        })->where('name', $betTypeName)->count();