How to use whereRelation method in Laravel

Categorized as Laravel

Laravel tip. You can use the whereRelation method (introduced in Laravel 8.57+) instead of whereHas when filtering by a simple where statement.

// Using whereHas
$bestsellerAuthors = Author::query()
  ->whereHas('books', function ($query) {
      $query->where('is_bestseller', true);

// using whereRelation
$bestsellerAuthors = Author::query()
  ->whereRelation('books', 'is_bestseller', true)

The only downside is that you cannot use scopes, whereRelation is suitable for only one simple “where” statement. The merit of using whereRelation is shorter and more readable syntax, and in terms of performance it is identical to whereHas.

See the official documentation.

via @cosmeescobedo

Leave a reply

Your email address will not be published. Required fields are marked *