duckz1209's avatar

WEEKDAY() wont work non sqlite database

i want to see all records based on dayofweek. this is my code:

$weeks = Book::whereRaw('WEEKDAY(created_at) = WEEKDAY(TODAY())')->get();

its good with mysql database but when i switch to sqlite, it wont accept the WEEKDAY() function. i need sqlite database.. is there any way to compare dayofweek on created_at and day today?

0 likes
3 replies
s4muel's avatar
s4muel
Best Answer
Level 50

not sure about it, but give it a try

//if you want to support multiple databases, switch the code, depending on DB::getDriverName()
//...

$weeks = Book::whereRaw("CAST (strftime('%w', date) AS Integer) = " . date('N'))->get();
burlresearch's avatar

When you're using whereRaw you are using database specific query strings. These, clearly, are not portable across database engines. Case in point: weekday() is a MySQL. function.

You could create a raw query using strftime('%w', 'now') in SQLite, but you're still tying that query to your database.

To do this in Eloquent, you could use a filter on the Carbon instance of the created_at field:

Book::all()->filter(function ($i) {
    return $i->created_at->dayOfWeek == Carbon::now()->dayOfWeek;
});

Please or to participate in this conversation.