PHP
Filtering by Related Columns with Eloquent `whereRelation`
Efficiently filter parent models based on direct conditions applied to related model columns using Laravel Eloquent's `whereRelation` method for optimized queries.
<?php
// app/Models/Order.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
// app/Models/User.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// ...
}
// Example: Find orders placed by users named 'John Doe'
$orders = Order::whereRelation('user', 'name', 'John Doe')->get();
// Example with multiple conditions or complex queries on the related model:
$recentOrdersFromActiveUsers = Order::whereRelation('user', function ($query) {
$query->where('status', 'active')
->where('last_login_at', '>', now()->subDays(30));
})->where('created_at', '>', now()->subMonth())->get();
How it works: The `whereRelation` method allows you to filter models based on conditions applied directly to the columns of a related model. Unlike `whereHas`, which checks for the *existence* of a related record satisfying a condition, `whereRelation` is optimized for directly comparing related model attributes, often translating into a more efficient SQL `JOIN` clause. It accepts the relationship name, the column name, and the value, or a closure for more complex conditions on the related model.