Search code examples
laraveleloquenteloquent-relationship

Laravel Eloquent check for relationship between two specific models


I have two models with a many to many relationship

Post and Category

I am trying to find out if a specific category belongs to a specific post.

I can see if a specific post has any categories, I'm tempted to just get all of the categories for the post and load it into an array then do an in_array check for the category I am looking for. Before I go that route is there a proper way to do this in Eloquent though?


Solution

  • You can do this like so:

    $post->categories()->where('id', $category->id)->exists();