Davit Zeynalyan
Davit Zeynalyan

Reputation: 8618

laravel eloquent collection orderby firstly null then filed value

I have $items with this Illuminate\Database\Eloquent\Collection instance. The result of dd($items->toArray()) is

array:3 [▼
  0 => array:3 [▼
    "id" => 10
    "start_date" => "Jan 1997"
    "end_date" => "Jan 2000"
  ]
  1 => array:3 [▼
    "id" => 9
    "start_date" => "Jan 2000"
    "end_date" => "Jan 2003"
  ]
  2 => array:3 [▼
    "id" => 6
    "start_date" => "Jan 2007"
    "end_date" => ""
  ]
]

I want to order by end_date. Firstly empty values than desc like this

array:3 [▼
  0 => array:3 [▼
    "id" => 6
    "start_date" => "Jan 2007"
    "end_date" => ""
  ]
  1 => array:3 [▼
    "id" => 9
    "start_date" => "Jan 2000"
    "end_date" => "Jan 2003"
  ]
  2 => array:3 [▼
    "id" => 10
    "start_date" => "Jan 1997"
    "end_date" => "Jan 2000"
  ]
]

How can do it in correct way. I try $items->sortByDesc('end_date') but that case empty values is the end

Upvotes: 0

Views: 36

Answers (1)

Leonardo Rossi
Leonardo Rossi

Reputation: 3032

You should implement your own sort function as mentioned in the documentation

you can do something like

$items = $items->sort(function($a, $b) {
    if ($a->end_date == '') { return -1; } // this will set the empty value always before the other
    // pseudo code
    $firstDate = \Carbon::parse($a->end_date);
    $secondDate = \Carbon::parse($b->end_date);
    if ($firstDate->lessThan($secondDate)) { return - 1; }
    if ($firstDate->equalTo($secondDate)) { return 0; }
    return 1;
});

Upvotes: 1

Related Questions