Home > OS >  Laravel 5 with eloquent relation callback function returning wrong records
Laravel 5 with eloquent relation callback function returning wrong records

Time:12-08

Here is User Model

public function userpackages()
{
    return $this->hasMany('App\UserPackages');
}

Trying to get users packages form specific month and year but it returning all records.

$users = User::with(['team', 'userpackages' => function($package) use($month,$year) {
    $package->whereMonth('created_at', $month)->whereYear('created_at', $year);
}])->get();

Fetching

foreach ($users as $key => $user) {
  $userpackages = $user->userpackages;
}

CodePudding user response:

If I'm understanding correctly, you are filtering the eager load, but this does not affect the models returned. You need to repeat the filter using whereHas() to limit the models that are returned. In addition, functions like whereDate() can be very inefficient, especially if the column is indexed. I suggest using whereBetween() when searching a date range.

$date = Carbon::createFromFormat("Y-m", "$year-$month");
$range = [$date->startOfMonth(), $date->endOfMonth()];

$users = User::with('team')
    ->with(['userpackages' => fn ($q) => $q->whereBetween('created_at', $range)])
    ->whereHas('userpackages', fn ($q) => $q->whereBetween('created_at', $range)
    ->get();

To explain further:

  • User::with('userpackages') returns all users, each with all of their packages.
  • User::with(['userpackages' => 'some condition']) returns all users, each with some of their packages
  • User::whereHas('userpackages', 'some condition') returns some users, each with all of their packages
  • User::(['userpackages' => 'some condition'])->whereHas('userpackages', 'some condition') returns some users, each with some of their packages.

CodePudding user response:

This is because your function needs to return the query. u are missing return statement.

$users = User::with(['team', 'userpackages' => function($package) use($month,$year) {

    return $package->whereMonth('created_at', $month)->whereYear('created_at', $year);

}])->get();
  • Related