Marcin Nabiałek
Marcin Nabiałek

Reputation: 111859

Syntax for creating conditional queries based on other variables in Laravel

I have a problem with using :: and -> operators for models

Let's assume I want to make some simple search. I can do it this way:

$model = SomeModel::where('id', '>', 2)->where('id', '<', 10)->get();

After model name I need to use :: operator and then standard -> operator.

But now assume we have $minId and $maxId in some variables and if those variables values are empty we don't want to use where conditions:

$minId = '';

$maxId = '';

$model = SomeModel::where('id','>','0'); // dummy where here

if ($minId != '') {
  $model = $model->where('id','>',$minId);
}
if ($maxId != '') {
  $model = $model->where('id','<',$maxId);
}
$model = $model->get();

The problem is how to use :: before conditions. You cannot use $model = SomeModel:: so I've added dummy where where('id','>','0') that is always true. Now in conditional where I can use -> operator without a problem.

Can it be done some other way without using extra condition?

Upvotes: 1

Views: 956

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81187

Get the query first (this is what eloquent will do anyway):

$query = Model::query();

if (..) { $query->where(..) }
if (..) { $query->where(..) }

$query->get();

And for something like this you can use scopes, for example:

// Model
public function scopeMinId($q, $id)
{
  if ( ! empty($id)) $q->where('id', '>=', $id);
}

Then you can easily use (no matter what minId and maxId is set to):

Model::minId($minId)->maxId($maxId)->get();

Upvotes: 4

Related Questions