Search code examples
phplaraveleloquenteloquent-relationship

Laravel Eloquent - Query with multiples parameters


I'm new to the Laravel framework and I could need a little help from you.

Could someone help me to convert this request into Eloquent ?

SELECT * FROM `non_working_days` WHERE YEAR(date) = "2021" AND (country = "Paris" OR country = "Madrid")

For the moment I have managed to find a solution but I am running as many queries as the number of parameters.

foreach ($calendar as $code) {
  array_push(
    $data,
    Model::query()
      ->whereYear('date', '=', $year)
      ->where('country', $code)
      ->get()
  );
}

So it comes down to doing :

SELECT * FROM `non_working_days` WHERE YEAR(date) = "2021" AND country = "Paris"
SELECT * FROM `non_working_days` WHERE YEAR(date) = "2021" AND country = "Madrid"

So I don't think it's very efficient knowing that potentially I would have many more parameters.

Thanks


Solution

  • You can use the whereIn method:

    $countries = ['Paris', 'Madrid']; // or use $calendar instead if it's an array
    $data = Model::query()
        ->whereYear('date', '=', $year)
        ->whereIn('country', $countries)
        ->get();
    

    This should give you a query like this:

    SELECT * FROM `non_working_days` WHERE YEAR(`date`) = "2021" AND `country` IN ("Paris", "Madrid");