Brent Brent - 2 months ago 12
PHP Question

Where and If Statements Laravel Eloquent

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

Answer

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