Search code examples
laravellaravel-query-builder

Laravel: Merge two query builders


I have a table of courses which will be free to access or an admin will need to click something to let users see the course.

The course table looks like this:

| id | title          | invite_only | 
|----|----------------|-------------|
| 1  | free course    | 0           |
| 2  | private course | 1           |

Separate from this I have a course_user table, where initially users request access, then admins can approve or deny access:

| id | user_id | course_id | approved | declined |
|----|---------|-----------|----------|----------|
| 1  | 3       | 2         | 1        | 0        |
| 2  | 4       | 1         | 0        | 1        |
| 3  | 4       | 2         | 0        | 0        |

I'd like to index all the courses a user has access to:

class User extends model{
  public function myCourses(){
    $public = $this->publicCourses;
    $invited = $this->invitedCourses;
    return $public->merge($invited);
  }
  public function publicCourses(){
    return $this
      ->hasMany('App\Course')
      ->where('invite_only', false);
  }
  public function invitedCourses(){
    return $this
      ->belongsToMany("\App\Course")
      ->using('App\CourseUser')
      ->wherePivot('approved', 1);
  }
}

How can I make the myCourses function return the results of both publicCourses and invitedCourses by doing only one database query? I'd like to merge the two query builder instances.


Solution

  • I was able to make a much simpler query, and use Laravel's orWherePivot to extract the correct courses:

    public function enrolledCourses()
    {
        return $this
          ->courses()
          ->where('invitation_only', false)
          ->orWherePivot('approved', true);
    }