LTKort's avatar

Simplify Eloquent / Laravel with multiple filters and pagination?

My question is about simplifyng multiple Eloquent queries that work with Laravel pagination.

I am building a Laravel website, on this website people can share certain recipes.

I have multiple variables that members can search, filter and look trough. So members can post recipes and add: - Type - Duration - Country - Platform

The idea is that there is page with all the recipes, but there are also pages where only recipes for 1, 2 or more filters are applied. E.g. cold 5 minute recipes or German Warm Long recipes.

Im using Laravel 5.7 and now im building all kind of queries with different where statements. Like this:

 public static function getRecipesMixFilter($cid, $pid, $tid, $did)
{
    $recipes = self::with(['member', 'platform', 'member.platform', 'member.duration', 'member.type'])->whereActive(1)->whereHas('member', function ($query) use ($cid, $pid, $tid, $did) {
            $query->where('country_id', '=', $cid)
            ->where('platform_id', '=', $pid)
            ->where('type_id', '=', $tid)
            ->where('duration_id', '=', $did);
    })->orderBy('updated_at', 'desc')->paginate(24);

    return $recipes;
}

But what is the easy way to do this? Now i have 15 different queries, where I feel it could be 1. So that the ->where('platform_id', '=', 1) etc. are optional.

When I try to filter on each object so first Platform, than Type and so on, I cant apply the pagination.

Is there a way to simplify this? And can I use Ajax filters with Laravel pagination?

0 likes
1 reply
jlrdw's avatar

You can build onto a query, I start with the part that will be there, i.e.,

$query = Dog::where('dogname', 'like', $dogsch);

then if another condition was passed in the request (check for) add it to the query:

$query->where('adopted', '=', 0);  // add as needed

finalize with your order by

$dogs = $query->orderBy('lastedit', 'DESC')->paginate(5);

Build the array for the appends, and pass that to view, i.e.,

$pagelinks = array('psch' => $dogsearch, 'aval' => $aval);

Which in view would be

echo '<td>' . $dogs->appends($pagelinks)->links() . '</td>';

Non blade example, just use blade instead.

Please or to participate in this conversation.