Matt Pierce
Matt Pierce

Reputation: 805

Laravel Get Collection for a Collection

I have 2 models, a User model and a Post model. I am trying to get a collection of Users that have posted between a certain date range. I am just lost on how to tie the 2 models together. There is a One-to-Many relationship between the two.

User Model:

public function posts()
{
    return $this->hasMany('App\Models\Post', 'user_id');
}

So, I want a collection of users where posts are between date 1 & date 2 AND if a user has posts between those dates, I want a collection of those posts. I know I can use whereBetween for a query builder, but can I use that for eloquent? Also, how do I sort the entire User model by the ones that have those posts? How about the filter() method?

$users = Users::all();

$users = $users->filter(function() {
   foreach ($users as $user)
   {
      if ($user->posts->whereBetween(date 1, date 2))
      { 
         return true; //something like that
      }
   }
});

Upvotes: 1

Views: 2770

Answers (1)

Zayn Ali
Zayn Ali

Reputation: 4915

It's better to eager load your relation model as you wanted and then work with the result. no need to use the if checks.

$users = Users::with(['posts' => function($query) {

    $query->whereBetween(date 1, date 2);

}])->get();

More Information: Eager Loading

Upvotes: 5

Related Questions