sandri
sandri

Reputation: 49

How to make Laravel Eloquent Query more dynamic?

Based on some inputs, whether they are not null, I want to perform a Eloquent Query. I want to add the following attributes to query if they are not null.

How to make this query work?

 $property = Property::
        where('published','=','1');

        if(!empty($searchInput)){
            $property+=$property
            ->orWhere('name', 'like', $percentageSearch)
            ->orWhere('village', 'like', $percentageSearch)
            ->orWhere('address', 'like', $percentageSearch)
            ->orWhere('reference_point', 'like', $percentageSearch)
            ->orWhere('price', 'like', $percentageSearch);
        }

        if(!empty($typeInput)){

            $property+=$property
            ->orWhere('type', '=', $typeInput);
        }

        if(!empty($categoryInput)){
            $property+=$property
            ->orWhere('category_id', '=', $categoryInput);
        }
        $prop=$property->get();

Upvotes: 0

Views: 111

Answers (1)

IGP
IGP

Reputation: 15786

Use a local scope and conditional queries.

$property = Property::where('published_at', 1)->search($searchInput, $typeInput, $categoryInput)->get();
// Property Model
public function scopeSearch($builder, $search, $type, $category)
{
    return $builder->where(function ($query) use ($search, $type, $category) {
        $query->when($search, function ($property, $search) {
                  $property->orWhere('name', 'like', $search)
                           ->orWhere('village', 'like', $search)
                           ->orWhere('address', 'like', $search)
                           ->orWhere('reference_point', 'like', $search)
                           ->orWhere('price', 'like', $search);
              })
              ->when($type, function ($property, $type) {
                  $property->orWhere('type', '=', $type);
              })
              ->when($category, function ($property, $category) {
                  $property->orWhere('category_id', '=', $category);
              });
    });
}

Upvotes: 1

Related Questions