laravel/framework — pull request #4267 by jarektkaczyk (2014-04-29 00:36:08+00:00)
Title: [Proposal] Easier querying relations with has-like method that accepts Model instance

This PR introduces Eloquent Builder's new method `hasIn()` that makes it easier to query relations in has-like manner and helps to keep relation abstract.

```
// You can do this:
Auth::user(); // hasMany Post, belongsToMany Category
$comment = Comment::find(5); // belongsTo Post
$category = Category::first(); // belongsToMany Post
$posts = Post::hasIn('comments', $comment) // simple usage
->hasInCategories($category) // or dynamic call
->orHasInUser(Auth::user()) // orHasIn / dynamic orHasInRelationName
->get();
```

Which has the same result to:
```
$posts = Post::whereHas('comments', function ($q) {
$q->whereId($comment->id);
})->whereHas('categories', function ($q) {
$q->where('categories.id', '=', $category->id);
})->orWhere('user_id', Auth::user()->id) // * see below
->get();
```
\* orWhere part in fact it is simpler in the 2nd example, but in case of any changes in the db schema and/or related model you would need to refactor every occurence of this code.
Proposed solution just does it without any changes, but rearranging relations on the moels if necessary.

Of course it might be used to query far relations too:
```
// for single Model:
Post::find(5)->categories()->hasInUsers(Auth::user())->get();

// or a collection mixed with whereHas():
Post::whereHas('category', function ($q) {$q->hasInUsers(User::first());})->get();
```

Method applies getQualifiedKeyName and getKey for checks and prevents from incorrect results by injecting Model not belonging to the provided relation.