In this post explain of how to use laravel whereRelation() and whereHas. If you have any question about relationship whereRelation then i will give easy example with solution.Â
Laravel’s Eloquent ORM provides powerful methods to query related models. Two commonly used methods for filtering relationships are whereRelation() and whereHas().Â
1. What is whereRelation() ? And how to use Laravel whereRelation()
The whereRelation() method is shorthand method to filter relationships based on conditions. It simplifies queries by directly specify the relationship and condition in a single line.
Syntax:
Model::whereRelation('relationship', 'column', 'operator', 'value')->get();
Example:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index()
{
$users = User::with('post')
->whereRelation('post', 'status', '=', 1)
->get()
->toArray();
dd($users);
}
}
Explanation:
- This query fetches all users who have at least one post with a status of active or deactive.
- The whereRelation() method allow you to specify relationship posts and the condition status = 1 or 0.
Read also:Â How to create custom class in Laravel 11?
2. What is whereHas()? And how to use Laravel whereHas()
The whereHas() method is used for more complex queries where you need to apply additional logic or use nested conditions.
Syntax:
Model::whereHas('relationship', function ($query) {
$query->where('column', 'operator', 'value');
})->get();
Example:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index()
{
$users = User::with('post')
->whereHas('post', function($query) {
$query->where('status', '=', 1);
})->get();
dd($users);
}
}
Explanation:
- The query fetches all users who have at least one post that is status = 1.
- The whereHas() method is more usable, allowing you to define complex condition within closure.
I hope this tutorial help you.