Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: dynamic where clause with Elouquent

I am calling URL with search params which are dynamic. How could I form proper Eloquent query?

In theory:

  1. query
  2. query where(someParam1)
  3. query where(someParam2)
  4. query orderby(someParam3)
  5. query get

I need this kind of structure so I can use where clause if param exists. If there is some other way in Laravel, please let me know.

like image 649
be-codified Avatar asked Jun 19 '15 16:06

be-codified


3 Answers

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();
like image 129
BakerStreetSystems Avatar answered Nov 11 '22 09:11

BakerStreetSystems


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.

like image 32
Koushik Das Avatar answered Nov 11 '22 09:11

Koushik Das


You can use like this

$validateUserDetail = User::query();
if (!empty($userDetails['email'])) {
    $validateUserDetail->whereemail($userDetails['email']);
}if (!empty($userDetails['cellphone'])) {
    $validateUserDetail->wherecellphone($userDetails['cellphone']);
}
$validateUserDetail->select('username');
$validateUserDetail->get()
like image 2
Nishabh Mistry Avatar answered Nov 11 '22 07:11

Nishabh Mistry