For getting every new tutorial link Please join our telegram group

Part 11 How to work laravel eloquent doesntHave() and whereDoesntHave() method with example

This laravel tutorial about how to work eloquent doesntHave() and whereDoesntHave() method for relationship with hindi video.


Also ask: doesntHave() method not working, where to use doesntHave() method, how to use where condition in doesntHave method.

How to work laravel doesntHave() method

Laravel doesntHave method just opposite of has() method. When we want to retrieve data that not have any children relationship data than use doesntHave.

Let understand by example A Video model have Some Comment and we retrive all videos that have not any comment than just use doesntHave('comments') here 'comments' relationship name which is define in model.

Video Model

Our model exist on this location app/Model/Video.php and here we define a comments relationship which get all comment data of a video.

<?php

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

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

Now we show only rows that have no comment data in controller use doesntHave() method.

<?php

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

class PostController extends Controller{
    public function index(){
       $videos = Video::doesnthave('comments')->get();

        dd($videos);
    }
}

How to work laravel whereDoesntHave() method

If you want to add where condition in doesnthave and get data that have no relationship data with where condition than use eloquent whereDoesntHave() method.

$videos = Video::whereDoesntHave('comments', function ($q) {
    $q->where('content', 'like', 'code%');
})->get();

If you want to make perfect laravel developer than you right place, this laravel tutorial on advanced web tutorial. here we provide laravel 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