Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select only records of the current week from Mysql Database Timestamp Laravel

I want to get only the records from monday to friday of the current week, but i'm having a hard time thinking and researching ways on how to do it, I found some ways on the internet but its so hard to understand for a newbie like me, so here is my code:

         $myquery=DB::table('attendances')
        ->leftJoin('employees', 'attendances.user_id', '=', 'employees.id')
        ->where('user_id', '=', $employee->id)

        //I want to do something like this one
         ->WHERE WEEK(`date`) = WEEK(NOW()  

        ->orderBy('attendances.date','asc')->get();

I implement some of the answers like this

         $myquery=DB::table('attendances')
        ->leftJoin('employees', 'attendances.user_id', '=', 'employees.id')
        ->where("WEEKOFYEAR(`date`)", "=", "WEEKOFYEAR(NOW())")
        ->where('user_id', '=', $employee->id)
        ->orderBy('attendances.logon','asc')->get();
like image 618
user3177305 Avatar asked Feb 12 '23 11:02

user3177305


1 Answers

You can use a whereBetween with two Carbon date instances:

->whereBetween('date', [
    Carbon\Carbon::parse('last monday')->startOfDay(),
    Carbon\Carbon::parse('next friday')->endOfDay(),
])

If you want to find all record in the current month, use this:

->whereBetween('date', [
    Carbon\Carbon::now()->startOfMonth(),
    Carbon\Carbon::now()->endOfMonth(),
])
like image 134
Joseph Silber Avatar answered Feb 14 '23 01:02

Joseph Silber