简体   繁体   中英

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();

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);
              });
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM