Filip_Zdravkovic's avatar

In a blade view, check if there is a relation between two specific models

I have two models with Many-to-Many relationship:

  • User model (users table)
  • Robot model (robots table)
  • (and there is robot_user table)

There is a robot profile page (blade view) which displays some info about the specific robot. In that blade file, when a user is logged in - I need to check if there is a relationship between that specific robot and logged in user. What is the best way to do it, what's the most elegant way?

0 likes
1 reply
rcubitto's avatar
rcubitto
Best Answer
Level 11

There are many ways, but since you're in a view, I'd suggest using the "tell, don't ask" approach. That is, encapsulate all the logic in a public method.

In the view I'd have something like

@if ($robot->isRelatedToAuthUser())
...
@endif 

And then, inside the Robot model

public function isRelatedToAuthUser() {
    return $this->users->contains(auth()->user());
}
1 like

Please or to participate in this conversation.