Using whereDate, whereYear, whereMonth, whereDay and whereCreatedAt for dates

Following snippets would be able to fetch records based on given magic where() methods.

01. whereCreatedAt - using exact value of created_at field to be matched in the tbl

$posts = Post::select([ 'id','title', 'created_at'])->whereCreatedAt('2022-07-22 18:54:38')->get();

02. whereDate - using only date part to be matched with created_at field in the tbl

// typical way
$posts = Post::select([ 'id','title', 'created_at'])->where('created_at', 'like' ,'2022-07-24%')->get();
// magical way
$posts = Post::select([ 'id','title', 'created_at'])->whereDate('created_at', '2022-07-24')->get();

03. whereYear - using only year part to be matched with created_at field in the tbl

$posts = Post::select([ 'id','title', 'created_at'])->whereYear('created_at', '2022')->get();

04. whereMonth - using only month part to be matched with created_at field in the tbl

$posts = Post::select([ 'id','title', 'created_at'])->whereMonth('created_at', '07')->get();

05. whereDay - using only day part to be matched with created_at field in the tbl

$posts = Post::select([ 'id','title', 'created_at'])->whereDay('created_at', '24')->get();

Related Posts


Using WhereIn

Updating multiple rows

Using Like

Using orWhere

What is Query Builder?

Using "with" in eloquent query

Getting last inserted id

Selecting last row of a table

Using parameters in find() method

Using local scope in eloquent

Using global scope in eloquent