Laravel Carbon Querying date with sameDay()

Viewed 2959

I'm trying to build up a query method in Laravel (5.8) to retrieve the entries made in current date (think at "Discover this day" from Facebook, it's kinda the same).

I have the following code:

$todayMementos = Memento::where(['user_id' => auth()->user()->id])
    ->whereDate('date', Carbon::isSameDay())
    ->get();

I tried to compare the date with this function; I'm using Carbon "isSameDay()" for it, not sure if it's the right function to choose but the result I want is this:

If in this DD-MM-no-matter-the-year, user has added some entries, give them to me.

Suggestions? Thank you in advance!

2 Answers

Retrieve day current day and month

$day = Carbon::now()->day;
$month = Carbon::now()->month;

You can use Eloquent filter for retrieving the same day and month.

$todayMementos = Memento::where(['user_id' => auth()->user()->id])
    ->whereDay('date', '=' $day)
    ->whereMonth('date', '=', $month)
    ->get();

You can do it by using carbon date formatting to get current date in yyyy-mm-dd format. This format is used by the database in sql.

$todayMementos = Memento::where(['user_id' => auth()->user()->id])
    ->whereDay('date',\Carbon\Carbon::now()->day)
    ->whereMonth('date',\Carbon\Carbon::now()->month)
    ->get();
Related