converting a DB:select() to query builder in laravel 7

Viewed 113

I have Users, Courses models with many-to-many relationship.

the pivot is the default one which contains:

id, user_id, course_id

my query is this:

DB::select("select * from courses where id <> any(select course_id from course_user where user_id='$user')")

the above query gets all courses that a specific user didn't enroll with.....now I want to convert the result to a query builder but i can't write it right....any suggestion? thanks in advance.

1 Answers

I believe you could use whereDoesntHave

Courses::whereDoesntHave('users', function($query) use ($user) {
  $query->where('id', $user);
})->get();
Related