Search code examples
laravellaravel-4eloquent

filtering a paginated eloquent collection


I am trying to filter a paginated eloquent collection, but whenever I use any of the collection methods, I lose the pagination.

$models = User::orderBy('first_name','asc')->paginate(20);

$models = $models->each(function($model) use ($filters) {
    if(!is_null($filters['type'])) {
        if($model->type == $filters['type'])
            return $model;
    }

    if(!is_null($filters['state_id'])) {
        if($model->profile->state_id == $filters['state_id'])
            return $model;
    }

    if(!is_null($filters['city_id'])) {
        if($model->profile->city_id == $filters['city_id'])
            return $model;
    }
});

return $models;

I am working with Laravel 4.2, is there any way to persist the pagination?


Solution

  • Expanding on mininoz's answer with your specific case:

    //Start with creating your object, which will be used to query the database
    
    $queryUser = User::query();
    
    //Add sorting
    
    $queryUser->orderBy('first_name','asc');
    
    //Add Conditions
    
    if(!is_null($filters['type'])) {
        $queryUser->where('type','=',$filters['type']);
    }
    
    if(!is_null($filters['state_id'])) {
        $queryUser->whereHas('profile',function($q) use ($filters){
            return $q->where('state_id','=',$filters['state_id']);
        });
    }
    
    if(!is_null($filters['city_id'])) {
        $queryUser->whereHas('profile',function($q) use ($filters){
            return $q->where('city_id','=',$filters['city_id']);
        });
    }
    
    //Fetch list of results
    
    $result = $queryUser->paginate(20);
    

    By applying the proper conditions to your SQL query, you are limiting the amount of information that comes back to your PHP script, and hence speeding up the process.

    Source: http://laravel.com/docs/4.2/eloquent#querying-relations