gmisslin's avatar

Check if RelationShip exists between two specific models

Hi,

I have two models : User and Project. There is a "Many To Many" relationship between them.

I have a fonction in a controller which retrieves a project by his token :

$project = Project::getByToken($request->tokenProject)->firstOrFail();

But before returning the collection, i want to check if the current user and the collection are related (Means that both are connected in the "project_user" table). So i would like to do something like that :

$project = Project::getByToken($request->tokenProject)->firstOrFail();
if($project->hasUser(Auth::id())
{
    return $project;
}

Is there a function which can actually check that ? I searched in every topics but without success...

0 likes
5 replies
tykus's avatar
tykus
Best Answer
Level 104

Add this to your project model - it checks that the Collection of users returned by the belongsToMany relationship method contains the given user

// Project.php
public function hasUser($user) {
    return $project->users->contains($user);
}
8 likes
gmisslin's avatar

Thank you very much ! That's the right answer :)

chrispage1's avatar

Just a note to anyone looking for a solution on this. @tykus solution would enforce the loading of all users, which on some systems could be thousands.

If you want to check the presence of a relationship, without loading all the records, I'd recommend running it as a query -

public function hasUser($user)
{
  return $project->users()
    ->where('user_id', $user->getKey())
    ->exists();
}
22 likes

Please or to participate in this conversation.