简体   繁体   中英

Query String Filtering with differnt values from same column

How can we filter by multiple values in a column? Example: ?name=comapny1&name=company2

Fore example I have 5 company's and I search for products belong ti company1 and company2 the result I want to get is: table with products that belongs to company1 and company2

This is my filter:

class ProductFilters extends QueryFilter
{
    // maker
    public function make($maker)
    {
        return $this->builder->where('company', $maker);
    }

And query filter:

<?php
/**
 * Created by PhpStorm.
 * User: dmitry
 * Date: 2017/05/10
 * Time: 2:26
 */

namespace App;


use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;

abstract class QueryFilter
{
    protected $request;

    protected $builder;

    public function  __construct(Request $request)
    {
        $this->request = $request;
    }

    public  function apply(Builder $builder)
    {
        $this->builder = $builder;

        foreach ($this->filters() as $name => $value) {
            if (method_exists($this, $name)) {
                call_user_func_array([$this, $name], array_filter([$value]));
            }

        }

        return $this->builder;
    }

    public function filters()
    {
        return $this->request->all();
    }

}

My form looks like this:

<form method="GET" action="/products" id="form1">
  <input type="checkbox" name="company[]" value="1">1</input>
  <input type="checkbox" name="company[]" value="2">2</input>
</form>

This is my controller:

public function index(Request $request, ProductFilters $filters)
    {
        $products    = Product::filter($filters)->paginate(30)->appends($request->all());
        return view('product.browse', compact('products' ));
    }

Basic example illustrating use of whereIn .

$companies = $request->company ?? [];
$products = Product::company($companies)->paginate(30);

class Product extends Model
{
    // ...

    public function company(Builder $query, ...$companies) 
    {
        return $query->whereIn('company', $companies);
    }

    // ...
}

Example using whereIn with OP's code.

class ProductFilters extends QueryFilter
{
    // ...

    public function make($maker)
    {
        return $this->builder->whereIn('company', (array) $maker);
    }

    // ...
}

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