Saimon
Saimon

Reputation: 25

multiple where and or condition in Laravel

How can I prepare the query condition about multiple where condition. I need to retrieve the records relating to the current year and month for the dataIT (start) and dataFT (end) relating to a name (cognome is lastname and nome is name) Considering that it must be valid for example dates starting and ending at the works of the current month: dataIT = 2021-04-30 and dataFT = 2021-05-01 or dataIT = 2021-05-10 and dataFT = 2021-06-10

    $result=DB::table('timbraturas')
            ->where('cognome',$cognome)
            ->where('nome',$nome)
            ->whereMonth('dataIT','=',Carbon::now()->month)
            ->whereYear('dataIT','=',Carbon::now()->year)

             **or (
                  ->whereYear('dataFT','=',Carbon::now()->year)
                  ->whereMonth('dataFT','=',Carbon::now()->month)
              )**

            ->orderBy('id','asc')
            ->get();
    return $result;

}

Upvotes: 0

Views: 174

Answers (1)

MaartenDev
MaartenDev

Reputation: 5811

A closure can be used with the orWhere option, this allows specifying multiple conditions.

 $result=DB::table('timbraturas')
            ->where('cognome',$cognome)
            ->where('nome',$nome)
            ->whereMonth('dataIT','=',Carbon::now()->month)
            ->whereYear('dataIT','=',Carbon::now()->year)
            ->orWhere(function($query) {
                  $query->whereYear('dataFT','=',Carbon::now()->year)
                  ->whereMonth('dataFT','=',Carbon::now()->month);
              })

Docs: https://laravel.com/docs/8.x/queries#or-where-clauses

Upvotes: 1

Related Questions