Did you try this ?
$getDates['startDate'] = $getTasks->min('start_date');
$getDates['endDate'] = $getTasks->max('end_date');
Why not make two DB calls with min and max aggregates methods (http://laravel.com/docs/4.2/queries#aggregates) ?
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hey all
Time for Gator to get somes learning :) Is there a better way to do this? I'm keeping it to 1 DB call and then 2 collection calls. Much appreciated.
public function getDateRange($id, $projectId)
{
$getDates = [];
$getTasks = $this->task
->where('author_id', '=', $id)
->where('milestone_id', '=', $$projectId)
->orderBy('start_date', 'desc')
->select('start_date' ,'end_date')
->get();
$getDates['startDate'] = $getTasks
->sortBy('start_date', SORT_REGULAR, false)
->first()
->start_date;
$getDates['endDate'] = $getTasks
->sortBy('end_date', SORT_REGULAR, true)
->first()
->end_date;
$getDates['date_diff'] = $getDates['endDate']->diff($getDates['startDate'])->days;
return $getDates;
}
I think sort on collection is not very efficient. Why not use a raw query ?
Not sure of syntax :
$getTasks = $this->task
->where('author_id', '=', $id)
->where('milestone_id', '=', $$projectId)
->orderBy('start_date', 'desc')
->select('start_date' ,'end_date')
->selectRaw('DATEDIFF(MIN(start_date), MAX(end_date)) as date_diff')
->get();
Please or to participate in this conversation.