Search code examples
mysqllaraveleloquentmany-to-manyrelational-database

Laravel 5.2 get user's notes and note's users


I have two tables:

the first

Is users table which contain user information including user id.

The Second

Is notes table which container user notes including note id.

I have relation many to many between them and I have my intermediate table between them that contain the user_id which matches note_Id.

Everything works perfectly but I want to get user notes and other users that have the same note.

For example

NOTE 1 users with id 1, 2, 3 can see it.

I want to use a query that get all the notes that the logged in user created and also other users that can view this note.

what I have tried

$usernotes  = User::where('id', '=', Auth::user() -> id) -> first();
@foreach($usernotes -> notes as $usernote)
      {{ $usernote -> title }}
@endforeach

This return all the user notes but doesn't return the all note's users.


Solution

  • This query will get users (except an authenticated one as you ask) that have the same notes a currently authenticated user has:

    Note::whereHas('users', function($q) {
        $q->where('id', auth()->user()->id);
    })->with(['users' => function($q) {
        $q->where('id', '<>', auth()->user()->id);
    }])->get();