List Birthday Kids of the Day Using Laravel

Asked

Viewed 107 times

3

I use the code below that gives me a list of birthdays per month, but would need for the current date. Example: today 09/04 and the list display.

$aniversariantesDoMes = Pessoa::whereMonth('dt_nasc', Carbon::now()->month)
            ->orderByRaw('day(dt_nasc) asc')->get();

$birthday = (as I would do?)

It must be something simple, but I really couldn’t.

  • whereDate in place of whereMonth?

  • I have tried with whereDate , then returns me an empty list

2 answers

4


As far as I can tell, you only want the day and the month of any date, so you can call the two corresponding methods

  • whereDay
  • whereMonth

Example:

$dataAtualCarbon = Carbon::now();

$aniversariantesDoMes = Pessoa::whereMonth('dt_nasc', $dataAtualCarbon->month)
    ->whereDay('dt_nasc', $dataAtualCarbon->day)
    ->orderByRaw('day(dt_nasc) asc')->get();

that way with Builder will serve for any database that the Framework Eloquent is available.

  • Thank you, it worked. That’s exactly what it was. I was just passing 1 parameter. I got it, thank you very much

  • if this is the answer to your question @Carlosfarias tick as the answer...

2

Virgilio’s answer should solve your problem, but I’m going to leave my answer with a little differential you might need. Let’s assume you need to list the birthday of the month and day in the same function. Then you can do this using the function when Laravel. So if you don’t pass the birthday parameter of the day, it will list only the one of the month.

// Você pegará o parâmetro da sua request
$aniversariantesDoDia = $request->input( 'aniversariantesDoDia', null);

$aniversariantesDoMes = Pessoa::whereMonth('dt_nasc', Carbon::now()->month)
            ->when( $aniversariantesDoDia, function ( $query ) use ( $aniversariantesDoDia ) {
                return $query->whereDay( 'dt_nasc', $aniversariantesDoDia );
            })
            ->orderByRaw('day(dt_nasc) asc')->get();
  • It really can be very useful, grateful!

  • 1

    Come on: instead of writing $aniversariantesDoDia = $request->input( 'aniversariantesDoDia' ) ? $request->input( 'aniversariantesDoDia' ) : null; just gotta do it like this: $aniversariantesDoDia = $request->input( 'aniversariantesDoDia' ); automatically is null at the standard value or $aniversariantesDoDia = $request->input( 'aniversariantesDoDia', null); to explain its default value ... which is already null just as an example.

  • 1

    Thanks @Virgilionovic did not know that the default value was null. I will edit here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.