Assume we have a posts table and a comments table. Now the post has a relationship with comments and the relationship is one post may have many comments. Now we want to fetch all the post that does not have comments. How we can write a query in this case?
Laravel provides an eloquent doesntHave() and whereDoesntHave method. Using this doesntHave, we can fetch all blog posts that don't have any comments. To do so, we can pass the name of the relationship to the doesntHave
and orDoesntHave
methods:
app/Http/Controllers/TutorialController.php
<?php
namespace App\Http\Controllers;
use App\Models\Post;
class TutorialController extends Controller
{
public function index()
{
return Post::doesntHave('comments')->get();
}
}
We may add additional query constraints to your doesntHave
queries like below:
app/Http/Controllers/TutorialController.php
<?php
namespace App\Http\Controllers;
use App\Models\Post;
class TutorialController extends Controller
{
public function index()
{
return Post::whereDoesntHave('comments', function ($query) {
$query->where('content', 'like', 'code%');
})->get();
}
}
We can also use whereDoesntHave for a nested relationship like:
app/Http/Controllers/TutorialController.php
<?php
namespace App\Http\Controllers;
use App\Models\Post;
class TutorialController extends Controller
{
public function index()
{
return Post::whereDoesntHave('comments.user', function ($query) {
$query->where('banned', false);
})->get();
}
}
Conclusion
Now we know laravel doesnthave with condition. Hope this laravel doesnthave relation example tutorial will help you to create wheredoesnthave in laravel.