Brent Brent - 1 year ago 67
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;

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.'%');

Answer Source

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