Skip to content
Advertisement

Laravel and Eloquent – applying different filters

I’m feeling stuck. 🙁

I want to be able to execute different SQL query, depending on the selected filters in my form:

//My initial query without any filters is this:
$dbQuery="SELECT * FROM "interactions" WHERE "user_id" = ".Auth::user()->getAttribute('id');
//Then depending on the selected filters the query may be any combination of the following:
if (request('contact_id')) $dbQuery.=" AND "contact_id" = ".request('contact_id');
if (request('product_id')) $dbQuery.=" AND "product_id" = ".request('product_id');
if (request('type')) $dbQuery.=" AND "type" LIKE "%".request('type')."%"";
if (request('description')) $dbQuery.=" AND "description" LIKE "%".request('description')."%"";
if (request('date')) $dbQuery.=" AND "date" >= ".request('date');

I have a class called “Interaction” which extends the Eloquent model and I need to be able to execute the above query or represent the same logic through it.

Any ideas on how I can achieve that will be greatly appreciated!

EDIT: Thanks to Brice (my personal hero today), here is what did the trick for me:

$query = Interaction::where('user_id', Auth::id());
$contact_id = request('contact_id');
$product_id = request('product_id');
$type = request('type');
$description = request('description');
$date = request('date');
if ($contact_id) $query->where('contact_id', $contact_id);
if ($product_id) $query->where('product_id', $product_id);
if ($type) $query->where('type', 'like', "%".$type."%");
if ($description) $query->where('description', 'like', "%".$description."%");
if ($date) $query->where('date', '>=', $date);
$interactions = $query->get();
return view('interactions.index',compact('interactions'));

Advertisement

Answer

I’d recommend using the eloquent query builder for this.

For example:

$query = Interaction::where('user_id', Auth::id());

$contact_id = request('contact_id');
$product_id = request('product_id');
$type = request('type');
$description = request('description');
$date = request('date');

if ($contact_id) {
    $query->where('contact_id', $contact_id);
}

if ($product_id) {
    $query->where('product_id', $product_id);
}

if ($type) {
    $query->where('type', 'like', "%$type%");
}

if ($description) {
    $query->where('type', 'like', "%$description%");
}

if ($date) {
    $query->where('date', '>=', CarbonCarbon::parse($date));
}

$results = $query->get();

If you have a lot of results, you may want to use pagination instead of fetching all results at the same time as shown above.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement