How to use whereHas with orWhereHas in Laravel?

Today, We want to share with you laravel wherehas.In this post we will show you wherehas laravel, hear for orwherehas laravel we will give you demo and example for implement.In this post, we will learn about laravel wherehas with condition with an example.

In this tutorial, I will explain you how to laravel wherehas eloquent. Here, you will how to use laravel eloquent whereHas() with condition to building a query in laravel application.

You’re confusing whereHas and with.

-> The with method will let you load the relationship only if the query returns true.
-> The whereHas method will let you get only the models which have the relationship which returns true to the query.

Read Also:  PHP Create ZIP File In Laravel Using Zipper package

Laravel WhereHas Eloquent Example

Laravel eloquent has, with and whereHas methods are very confusing for programmers.

Laravel WhereHas then orWhereHas Example
Laravel WhereHas then orWhereHas Example

how to use whereHas and orWhereHas in laravel 6, laravel 7 and laravel 8 application?

here I can use eloquent wherehas than orwherehas when I used relationship in laravel application.

public function myProducts()
{
    $products = Product::with(['pcode', 'pstatus']);
   
    if ($request->has('name')) {
         $products = $products->whereHas('pcode', function( $query ) use ( $request ){
                      $query->where('name', $request->name);
                  })->orWhereHas('pstatus', function( $query ) use ( $request ){
                      $query->where('name', $request->name);
                  });
    }
   
    $products = $products->get();
  
    dd($products);
}

WhereHas

Laravel eloquent whereHas() function works basically the same as has() but it just allows you to specify additional filters for the related model to check.
Product > hasMany > Type

$products = Product::whereHas('types', function($q){
    $q->where('created_at', '>=', '2022-01-01 00:00:00');
})->get();
// only products that have types from 2022 on forward are returned

using Has

Laravel eloquent has() function is used to filter the selecting model based on the selected relationship. It works similarly to where function for relations.
Product > hasMany > Type

$products = Product::has('types')->get();
// only products that have at least one type are contained in the collection

using With

Laravel with() eloquent function is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify.
Product > hasMany > Type

$products = Product::with('types')->get();
foreach($products as $product){
    $products->types; // types is already loaded and no additional DB query is run
}

I hope you get an idea about has in laravel.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.