Support the ongoing development of Laravel.io →
posted 11 years ago
Eloquent

Hello,

I'm working on a filtering system, where I need to find users which have certain properties depending on relations.

To be more specific, a user has one user_profile which belongs to a year_group.

Depending on the input, a user should be filtered on the fields user_profile.region and user_profile.year_group_id. This resulted in the following try:

<?php
$query = Model\User::where('type', '=', $member)
    ->with('profile.yearGroup')
    ->orderBy('lastname');
$with = array();

if(Input::has('region')) {
  // (...)
  $with['profile'] = function($q) use ($region) {
    $q->where('region', '=', $region);
  }
}

if(Input::has('yeargroup')) {
  // (...)
  $with['profile'] = function($q) use ($yeargroup) {
    $q->where('year_group_id', '=', $yeargroup);
  }
}

$query ->with($with);
$memberlist = $query ->paginate(10);
?>

However, (1) one problem is that $with['profile'] is (obviously) overwritten and (2) this still selects all users, while I want to select only those which satisfy all where conditions and (3) I want to use the year_group-data as well.

So, in summary, what I actually would like to do is to select those members which have user.type=?, user_profiles.region=? and user_profiles.year_group_id=? and eager load the year groups.

How should I tackle these problems?

Last updated 3 years ago.
0

This post post might give you an idea.

Last updated 3 years ago.
0
  1. First collect needed constraints from Input, then apply where() in a loop for whereHas()
  2. For this use whereHas(), like in linked post, using data from 1
  3. Your current setup will do the job: with('profile.yearGroup'), but this will load all the related models, not filtered. So should you need only filtered, use the constraints on this too.
Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

haampie haampie Joined 5 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.