Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel get rows with specific day and month

I have the following query in laravel:

$eventos = EventsData::join('tbl_users', 'tbl_users.id_user', '=', 'tbl_events.id_user')
            ->where('tbl_users.birth_date', '>=', date("m-d"))  //my error
            ->where('tbl_events.year', '>=', date("Y"))
            ->get();

I have a users table (tbl_users), with the date of the birthdays of each user. And an events table (tbl_events), which records the anniversary of each user. Thus creating a table that will get the next birthdays.

My birth_date is type "yyyy-mm-dd". The table events is the year. I want to get the next event on the current day and year.

ie I think the anniversary date must be greater than the current month and day, and the event with the top year to the current year

like image 505
pc_oc Avatar asked Dec 15 '25 02:12

pc_oc


1 Answers

Format the birth_date to mm-dd first before comparing it to date('m-d'), like so:

$eventos = EventsData::join('tbl_users', 'tbl_users.id_user', '=', 'tbl_events.id_user')
            ->whereRaw("DATE_FORMAT( tbl_users.birth_date, '%m-%d') >= ?", array(date('m-d')))
            ->where('tbl_events.year', '>=', date("Y"))
            ->get();

Update

If your tbl_events doesn't have a full date attribute, you could do this in 2 queries:

First, get the remaining events of this year:

$events_this_year = EventsData::join('tbl_users', 'tbl_users.id_user', '=', 'tbl_events.id_user')
                ->whereRaw("DATE_FORMAT( tbl_users.birth_date, '%m-%d') >= ?", array(date('m-d')))
                ->where('tbl_events.year', '=', date("Y")) // Get remaining events this year
                ->get();

Second, get the events for next years:

$events_following_year = EventsData::join('tbl_users', 'tbl_users.id_user', '=', 'tbl_events.id_user')
                    ->where('tbl_events.year', '>', date("Y")) // Get events for upcoming years
                    ->get();

Then merge them

$eventos = $events_this_year->merge($events_following_year);
like image 194
sunny_skellington Avatar answered Dec 16 '25 18:12

sunny_skellington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!