How to get none related objects of Many to Many relationship

Posted 4 months ago by agilasadi

I have users and news table and then a middle table called news_user, the middle table determines which news has been seen by the user. I can easily get objects that have been seen but, but now I need to show the user objects that have not been seen.

I did a workaround with putting all the seen news id in an array and look for news where id differs from the array. but I don't consider it as the healthiest solution.

This is what I did:

$seenNewses = DB::table('news_user')->where('user_id', Auth::id())
->pluck('news_id')->toArray();
$notSeenNewses = News::whereNotIn('id', $seenKeepers)
->orderBy('id', 'asc')->first();

Is there a way I can do this with a single query?

P.S: I have seen similar questions but they got me a little confused. Any answer is appreciated.

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.