Eem Jee
Eem Jee

Reputation: 1319

How to make a whereIn query builder in Laravel Eloquent with empty parameter

I have made a query in Laravel Eloquent to search in table.

public function searchContest($search){
    $category = [];
    $area = [];

    if(isset($search['area'])){
        $area = $search['area'];
    }

    if(isset($search['category'])){
        $category = $search['category'];
    }

    $qry = self::whereIn('area',$area)
                ->whereIn('category', $category)
                ->get();
    var_dump($query);
    return;
}

But sometimes, area or category is empty and whereIn does not work with it. I'm not able to find any working solutions in the net. How can I make such a query?

Upvotes: 0

Views: 1426

Answers (3)

Murat Tutumlu
Murat Tutumlu

Reputation: 780

$q = self::query();
if (isset($search['area'])) {
  $q->whereIn('area', $search['area']);
}
if (isset($search['category'])) {
  $q->whereIn('category', $search['category']);
}
$qry = $q->get();

Upvotes: 1

nakov
nakov

Reputation: 14318

Or you can take advantage of the conditional clauses as here

DB::table('table_name')
    ->when(!empty($category), function ($query) use ($category) {
          return $query->whereIn('category', $category);
    })
    ->when(!empty($area), function ($query) use ($area) {
          return $query->whereIn('area', $area);
    })
    ->get();

Upvotes: 7

Omar Makled
Omar Makled

Reputation: 1876

You can use query scope inside the entity

    public function scopeArea($query, $ids)
    {
        if (! $ids) {
            return ;
        }
        return $query->whereIn('area', $ids);
    }

    public function scopeCategory($query, $ids)
    {
        if (! $ids) {
            return ;
        }
        return $query->whereIn('category', $ids);
    }

Now you can build the query

    $entity
        ->area($area)
        ->category($category)
        ->get();

https://laravel.com/docs/5.7/eloquent#query-scopes

Upvotes: 0

Related Questions