Search code examples
mysqllaraveleloquentmany-to-manyrelational-database

Laravel get data from two tables connected with many to many relationship


Guys I have 2 tables first is users second is notes:

I am connecting both tables with Many to many relationship

users, notes and user_note tables

See the 3 tables image

Now I am trying to get logged in user notes where I have logged in user id by Auth::user() -> id also I am trying to get all the other users that can see the same note.

For example

user_id=1 can see note_id=2 also user_id=2 can see note_id=2.

So note_id=2 have 2 users.

Problem:

I want eloquent that get me all the logged in user's notes and other users that share the same note.

I have tried whereHas but I couldn't get what I need.


Solution

  • Try this:

    $loggedInUser = Auth::user();
    $notes = $loggedInUser->notes()->with('users')->get();