Laravel Eloquent whereHas() Conditional Usage Guide

In this tutorial, we will delve into Laravel’s whereHas() condition within Eloquent relationships. Working with relationships is a common task in Laravel applications, and sometimes, you might want to apply conditions to these relationships. In such cases, the whereHas() method comes in handy. This article is a step-by-step guide for implementing the whereHas() method in…

By.

min read

In this tutorial, we will delve into Laravel’s whereHas() condition within Eloquent relationships. Working with relationships is a common task in Laravel applications, and sometimes, you might want to apply conditions to these relationships. In such cases, the whereHas() method comes in handy.

This article is a step-by-step guide for implementing the whereHas() method in Laravel.

 

Before diving into the examples, let’s first understand the whereHas() method and its significance in Laravel Eloquent relationships. We’ll also look at an alternative method called whereRelation().

 

What is Laravel Eloquent whereHas()

The whereHas() method allows you to apply a condition to a related model within a query. For instance, if you have users with a country relationship, and you want to filter these users based on their country, you can use the whereHas() method. In this section, we will showcase two examples, one using whereHas() and the other using whereRelation().

 

Example 1: Using whereHas()
public function index()
{
    $countryName = 'india';
    $users = User::with('country')
                    ->whereHas('country', function (Builder $query) use($countryName){
                        $query->where('name', 'like', '%'.$countryName.'%');
                    })
                    ->get()
                    ->toArray();
  
    dd($users);
}

 

Example 2: Using whereRelation()
public function index()
{
    $countryName = 'india';
  
    $users = User::with('country')
                    ->whereRelation('country', 'name', 'like', '%'.$countryName.'%')
                    ->get()
                    ->toArray();
  
    dd($users);
}

 

Full Implementation of the Examples

Before proceeding, let’s examine the table data with screenshots and the models’ code for both examples.

Models Code:

app/Models/User.php

<?php
  
namespace App\Models;
  
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
  
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
  
    protected $fillable = [
        'name',
        'email',
        'password',
    ];
  
    protected $hidden = [
        'password',
        'remember_token',
    ];
  
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
  
    public function country()
    {
        return $this->belongsTo(Country::class);
    }
}

app/Models/Country.php

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Country extends Model
{
use HasFactory;
}

 

Controller Code:

app/Http/Controllers/ExampleController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
  
class ExampleController extends Controller
{
    public function index()
    {
        $countryName = 'india';
        $users = User::with('country')
                        ->whereHas('country', function (Builder $query) use($countryName){
                            $query->where('name', 'like', '%'.$countryName.'%');
                        })
                        ->get()
                        ->toArray();
  
        dd($users);
    }
}

 

Output:

The output of the examples would look like:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Freaky Jolly
            [country_id] => 2
            [email] => [email protected]
            [email_verified_at] => 
            [two_factor_secret] => 
            [two_factor_recovery_codes] => 
            [current_team_id] => 
            [profile_photo_path] => 
            [created_at] => 2023-02-12T07:22:28.000000Z
            [updated_at] => 2023-02-13T10:10:19.000000Z
            [deleted_at] => 
            [country] => Array
                (
                    [id] => 2
                    [name] => US
                    [code] => 2
                    [created_at] => 2023-02-12T07:22:28.000000Z
                    [updated_at] => 2023-02-13T10:10:19.000000Z
                )
        )
)

 

Conclusion

We hope this tutorial was helpful in understanding how to use the whereHas() method and whereRelation() method in Laravel Eloquent relationships. These methods provide a powerful way to apply conditions to related models within your queries, allowing for more advanced filtering of data in your applications.

Leave a Reply

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