35

I have built a multi filter search for my website but I cant seem to find any documentation on multiple if statements inside of where for my search.

Returns Lots of Results

$data = Scrapper::paginate(15);

Returns none.. need it to be this way to have where statements with IF see bellow.

$database = new Scrapper;
$database->get();

Example of what I want to do..

    $database = new Scrapper;
    if (isset($_GET['cat-id'])) {
        $database->where('cat_id', '=', $_GET['cat-id']);
    }
    if (isset($_GET['band'])) {
        $database->where('price', 'BETWEEN', $high, 'AND', $low);
    }
    if (isset($_GET['search'])) {
        $database->where('title', 'LIKE', '%'.$search.'%');
    }
    $database->get();
JofryHS
  • 5,804
  • 2
  • 32
  • 39
Brent
  • 2,385
  • 10
  • 39
  • 63

2 Answers2

52

Very similar to this: Method Chaining based on condition

You are not storing each query chains.

$query = Scrapper::query();

if (Input::has('cat-id')) {
    $query = $query->where('cat_id', '=', Input::get('cat-id'));
}
if (Input::has('band')) {
    $query = $query->whereBetween('price', [$high, $low]);
}
if (Input::has('search')) {
    $query = $query->where('title', 'LIKE', '%' . Input::get($search) .'%');
}

// Get the results
// After this call, it is now an Eloquent model
$scrapper = $query->get();

var_dump($scrapper);
Community
  • 1
  • 1
JofryHS
  • 5,804
  • 2
  • 32
  • 39
44

Old question but new logic :)

You can use Eloquent when() conditional method:

Scrapper::query()
    ->when(Input::has('cat-id'), function ($query) {
        $query->where('cat_id', Input::get('cat-id'));
    })
    ->when(Input::has('band'), function ($query) use ($hight, $low) {
        $query->whereBetween('price', [$high, $low]);
    })
    ->when(Input::has('search'), function ($query) {
        $query->where('title', 'LIKE', '%' . Input::get('search') .'%');
    })
    ->get();

More information at https://laravel.com/docs/5.5/queries#conditional-clauses

ChewySalmon
  • 576
  • 5
  • 22
fsasvari
  • 1,891
  • 19
  • 27