Search code examples
laraveleloquentlaravel-collection

Put items with date = today first in collection (Laravel)


I have a collection of all events $events = App\Event::orderByDesc('start_date')->get(). Now I want to put the events of today first, while keeping the order of the other events. I think I should use reject() and prepend(), but I am not able to combine both..


Solution

  • You can try make use of the partition method of collection like so:

    // Create 2 collections, One for today's event and another for the other days
    list($todays, $otherDays) = App\Event::orderByDesc('start_date')->get()->partition(function($event){
      // NOTE: change the date comparison as necessary such as date format. I assume you use carbon here
      return $event->start_date === \Carbon\Carbon::today()->toDateString();
    }
    
    $events = $todays->merge($otherDays);
    
    

    As an alternative, I found this post that makes use of the reject method. For your case the code will be something like:

    $filterFunc = function($event){
      return $event->start_date === \Carbon\Carbon::today()->toDateString();
    }
    
    $collection = App\Event::orderByDesc('start_date')->get();
    
    $events = $collection->filter($filterFunc)->merge($collection->reject($filterFunc));