Search code examples
laraveleloquentwhere-in

Laravel whereIn return only item of each


I have the following Eloquent query

Task::whereIn('user_id', [5,6,7,8])
            ->onlyActive()
            ->with('user')
            ->get();

which works perfect. The problem is that each user_id can have multiple Tasks, but i do only want to return one Task of each user_id.

Any ideas?


Solution

  • Easiest would be to define a new relationship on User model to get the latest Task - if that works for you

    class User extends Model
    {
        public function tasks()
        {
            return $this->hasMany(Task::class);
        }
    
        public function latestTask()
        {
            return $this->hasOne(Task::class)->latest();
        }
    }
    

    Then to query one active Task for each user

    User::whereIn('id', [5,6,7,8])
        ->with(['latestTask' => function($query){
            $query->onlyActive();
        }])
        ->get();