laravel-whererelation-replace-wherehas-tip.png
Шаблон кодуLaravel

Laravel whereRelation(): Replace Unnecessary whereHas() Callbacks

When a relationship filter needs one simple condition, whereRelation() removes the extra whereHas() callback while keeping the same query intent explicit.

For a simple condition on a related model, whereHas() can add more ceremony than actual query logic.

When you only need to check relationship existence with one basic condition, whereRelation() expresses the same intent with less callback noise.

Replace a Simple whereHas() Callback

До
php
Post::query()    ->whereHas(        'author',        fn ($query) =>            $query->where('active', true),    )    ->get();
Після
php
Post::query()    ->whereRelation(        'author',        'active',        true,    )    ->get();

Here the callback does not contain separate complex logic. It only forwards one condition to the relationship query, so whereRelation() makes the actual filter easier to see.

The intent stays the same: return only Post models for which a related author exists and matches the condition.

You Can Pass an Operator

PHP - whereRelation() with an operator
Post::query()    ->whereRelation(        'author',        'rating',        '>=',        4,    )    ->get();

The shape is close to a normal where(): relation, column, operator, and value. For equality, you can omit the explicit operator.

When whereHas() Is Still Better

PHP - whereHas() for multiple conditions
Post::query()    ->whereHas(        'author',        fn ($query) => $query            ->where('active', true)            ->where('verified', true)            ->whereNotNull('email_verified_at'),    )    ->get();
whereRelation() is strongest for a short inline condition. If the callback contains several conditions, grouping, or more complex relationship logic, whereHas() is usually easier to read.

The useful rule is not to replace every whereHas(). If the callback exists only to hold one where(), check whether whereRelation() communicates the same intent more directly.

#eloquent #laravel-12 #laravel-13 #php-8-4 #php-8-5 #where-relation #where-has #relationship-queries

Схожі поради

laravel-withwherehas-avoid-duplicate-conditions-tip.pngПорада
Переглянути пораду
#eloquent #laravel-12 #laravel-13 #php-8-4 #php-8-5 #where-has #with-where-has #eager-loading #relationships
laravel-tap-side-effects-keep-original-value-tip.pngПорада
Переглянути пораду
#eloquent #laravel-12 #laravel-13 #php-8-4 #php-8-5 #tap #helpers #tappable
laravel-firstorcreate-replace-first-create-tip.pngПорада
Переглянути пораду
#eloquent #laravel-12 #laravel-13 #php-8-4 #php-8-5 #model-persistence #first-or-create #first-or-new
laravel-updateorcreate-replace-first-if-tip.pngПорада
Переглянути пораду
#eloquent #laravel-12 #laravel-13 #php-8-4 #php-8-5 #update-or-create #model-persistence #upsert