Reputation: 1708
I'm making my first laravel project, using postgres, and I'd like to be able to access all the people with a birthday this month (my people table has a birthdate field that's a date). I've looked around and I can't figure out the right syntax for accessing the month and comparing with the current month.
I've tried a few ways in my controller:
1) here the arrow operator is unexpected for birthdate->month:
public function get_birthday_people()
{
$this_month = \Carbon\Carbon::now()->month;
$birthday_people = Person::all()
->Where('birthdate'->month, $this_month)
->Where('active', true)
->get();
return $birthday_people;
}
2) here I get Call to undefined method Illuminate\Database\Eloquent\Collection::whereMonth():
public function get_birthday_people()
{
$birthday_people = Person::all()
->whereMonth('birthdate', '=', Carbon::now()->month)
->Where('active', true)
->get();
return $birthday_people;
}
What's the right way to do this?
Upvotes: 2
Views: 2974
Reputation: 4168
Try somethind like this
$birthday_people = Person::all()
->where("date_trunc('month', birthdate)", "=", Carbon::now()->month)
->where("active", true)->get();
OR
$birthday_people = Person::all()
->where("extract(MONTH from birthdate)", "=", Carbon::now()->month)
->where("active", true)->get();
Extract is equal to MySQL MOTNH() or YEAR() and etc. Ref
Upvotes: 2