DEV Community

Ibrahim
Ibrahim

Posted on

Querying Relationships in Laravel with whereRelation

Laravel's query builder provides the whereRelation method, which is very useful for querying relationships.

Here's the syntax for using the whereRelation method:

Model::whereRelation('relation', 'column', 'operator', 'value')
// or, using the default (=) operator
Model::whereRelation('relation', 'column', 'value')
Enter fullscreen mode Exit fullscreen mode

Suppose there is an Order model that has a hasMany relationship with the OrderItem model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{

    public function items() {
        return $this->hasMany(OrderItem::class);
    }   

}
Enter fullscreen mode Exit fullscreen mode

Now, let's say we want to get all orders that have items with a quantity greater than 100. This can be done using the whereRelation method. For example:

$ordersWithMinimumItemQty = Order::whereRelation('items', 'quantity', '>', 100)
    ->get();
Enter fullscreen mode Exit fullscreen mode

Behind the scenes, the whereRelation method actually calls the whereHas method. For example:

$ordersWithMinimumItemQty = Order::whereRelation('items', 'quantity', '>', 100)
    ->get();
// Equivalent to using whereHas:
$ordersWithMinimumItemQty = Order::whereHas('items', function ($query) {
        $query->where('quantity', '>', 100);
    })->get();
Enter fullscreen mode Exit fullscreen mode

As you can see, whereRelation simplifies the use of the whereHas method.

Top comments (0)