2 months ago

Is possible to build Eloquent queries with optional parameters?

Posted 2 months ago by RafaelMunoznl

I am running two queries that are pretty much the same, one for ALL users and given the ID one for an specific user.

Instead using two methods that would be practically the same, I am using just one and passing the ID as option like this:

public function otherDay($date, $employeeId = null)
   { … 

But now I want to hold the appointments from the previous day and the next day. And the issue repeats itself. I am passing a flat $str that could be previous or next. My method looks now like this:

   public static function otherDay($date, $str, $employeeId = null)

Then I sort all the condictions using IF statements:

$str == 'previous' ? $datum = ($date)->subDays(1) : $datum = ($date)->addDays(1);
$datum = substr($str->translatedFormat('d M Y'), 0, 10);

if (isset($employeeId)) {
 $newDay = Appointment::where('employee_id', $employeeId)->whereDate('date', 'like', '%' . $datum . '%')->get();
} else {
 $newDay = Appointment::whereDate('date', 'like', '%' . $datum . '%')->get();

I am publishing here a simplification of much longer queries. In real life they are much longer. I use with, select and where all over the place

They are in fact the same with the only difference of this statement:

where('employee_id', $employeeId)

My question is: Is it possible to pass optional subqueries and get rid of the IF statement and run just one query dynamically. Something like this:

$subq = “->where('employee_id', $employeeId)”

And then make:

$newDay = Appointment:: . $subq . ->whereDate('date', 'like', '%' . $datum . '%')->get();

I am having the similar problem everywhere in my App. I have to choose between:

  • all users or one user
  • previosday or nextday
  • manager or employee
  • client or superclient

Therefore, I would almost cut my methods or queries to the half.

Any suggestion?

Please sign in or create an account to participate in this conversation.