Patryk Przybylski
Patryk Przybylski

Reputation: 53

laravel 5.4 Common data from the database for different uses

I have a pivot table where the user id and project id are located. I would like to draw all joint projects for 2 different users. How to do it? I am currently downloading all projects for a logged-in user, but I would also like to download projects for a logged-in user and for example a user with id 2. This is what i have now:

$user = User::findOrFail(Auth::user()->id);
$projects = $user->projects;

Upvotes: 1

Views: 47

Answers (2)

MyLibary
MyLibary

Reputation: 1771

OK, so after reading your question carefully again, I would go the other way around.

I assume that you've a Project model and that you also set a users relationship in the model.

$projects = Project::whereHas('users', function ($query) {
    $query
      ->where('id', Auth::user()->id)
      ->where('id', 2);
})->get();

Is that what you were looking for?

Upvotes: 0

Jeff
Jeff

Reputation: 25221

You could fetch the second user's projects with a condition:

$user = User::findOrFail(Auth::user()->id);
$projects = $user->projects;
$user2 = User::findOrFail(2);
$sharedProjects = $user2->projects()->whereIn('id', $projects->pluck('id'))->get();

Upvotes: 2

Related Questions