j_watson's avatar

TIMEDIFF() in Laravel

I am trying to find the difference between two DateTime type columns in minutes using Laravel's query builder. I am aware of PHP's TIMEDIFF() function, however, Laravel doesn't seem to have such a function. Any ideas to replicate TIMEDIFF() in Laravel or maybe I missed it in the documentation.

0 likes
2 replies
Dhakalsandeep's avatar

You can use native sql function in selectRaw() based on your database to get the desired result. For MYSQL =>

selectRaw('TIMESTAMPDIFF(minute, start_date, end_Date) as duration')

However if you want to get it through model you can use

class Project extends Model
{
	public function getDifferenceInMinutes() {
        $from = \Carbon\Carbon::parse($this->start_date);
        $to = \Carbon\Carbon::parse($this->end_date);
    
        $diff_in_minutes = $to->diffInMinutes($from);
    
        return $diff_in_minutes;
    }
}

Note: the start_date and end_date are columns in your database table that corresponds to Project Model.

Now in your controller you can use

$project = Project::find(1);
dd($project->getDifferenceInMinutes());

Please or to participate in this conversation.