How to Querying Relations in Laravel
Since all types of Eloquent relationships are defined via methods, you may call those methods to obtain an instance of the relationship without actually executing the relationship queries.
In addition, all types of Eloquent relationships also serve as query builders, allowing you to continue to chain constraints onto the relationship query before finally executing the SQL against your database.
Example:
$user->posts()
->where('active', 1)
->orWhere('votes', '>=', 100)
->get();
// select * from posts
// where user_id = ? and active = 1 or votes >= 100
In most situations, you likely intend to use constraint groups to logically group the conditional checks between parentheses:
use Illuminate\Database\Eloquent\Builder;
$user->posts()->where(function (Builder $query) {
return $query->where('active', 1)
->orWhere('votes', '>=', 100);
})->get();
// select * from posts
// where user_id = ? and (active = 1 or votes >= 100)