For getting every new tutorial link Please join our telegram group

Part 10 laravel eloquent relationship has vs whereHas method by example with hindi video

In this laravel relationship tutorial we will discuss has() vs whereHas() method by example with hindi video tutorial.


Also ask: difference between has() vs whereHas() method, use of has vs whereHas method, whereHas() method not working, why we use laravel has() and whereHas() method and how to check relationship data exist or not.

Laravel has() and whereHas() method with example

Laravel has() method

Laravel Has method use on relationship data for check it exist or not. has method pass a relationship name like has('comments'). let a Post model have a many-to-many relationship 'comments' a post have many comments data. Than if we use has('comments') method on Post model in controller than it get post data that have at least one comment.

Post Model

In below example a Post model define which contain a hasMany method comments().

<?php

namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Post extends Model {
    
    public function comments() {
        return $this->hasMany(Comment::class);
    }
}
PostController

Below a Postcontroller which index method print posts data which has at least one comment data.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller{
    public function index(){
       $posts = Post::has('comments')->get();

        dd($posts);
    }
}

Laravel whereHas() method

If you want to get model data by relationship existing with extra where condition add in relationship than use whereHas() method it same work as has() method. Example of whereHas() condition

PostController
<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller{
    public function index(){
       $posts = Post::whereHas('comments', function($q){
           $q->where('status','1');
       })->get();

        dd($posts);
    }
}

What is the difference between laravel has() vs whereHas() method

the only difference between has and whereHas is has() method pass only relationship name and check data existence whereas whereHas() method pass relation name and also apply some conditions and filters on relationship.

You read this laravel tutorial on advanced web tutorial. here we provide laravel beginners to advanced tutorial in hindi video.

php laravel developer anmol sharma

Anmol Sharma

I am a software engineer and have experience in web development technologies like php, Laravel, Codeigniter, javascript, jquery, bootstrap and I like to share my deep knowledge by these blogs.

Related tutorial links