Laravel: dynamic where clause with Elouquent

You can just use the where statement. For ex: on users table or User model, you want dynamic search on name, id. You can do this

$where = [];
$firstName = $request->get('first_name');
if ($firstName) $where[] = ['first_name', 'like'. '%' . $firstName . '%'];
$id = $request->get('id');
if ($id) $where[] = ['id', $id];
$users = User::where($where)->get();

By default, it will return all the users, if anything exists in $where array, it will apply the where condition on that.


It's easy with Laravel. Just do something like this:

$query = User::query();

if ($this == $that) {
  $query = $query->where('this', 'that');
}

if ($this == $another_thing) {
  $query = $query->where('this', 'another_thing');
}

if ($this == $yet_another_thing) {
  $query = $query->orderBy('this');
}

$results = $query->get();