It is good practice to load relationship data after checking like when we loop through over data, we should check whether data exists or not. In the same way, we should check laravel query relationship existence before loading relational data. Laravel provides has() method to check laravel query relationship existence. 

Now in this tutorial, we will fetch all posts that have at least one comment. How we can do it? We can do it very easily using has() helper method. has() helper method expects a relation. So let's see the query of laravel where relationship has value.

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\Post;

class TutorialController extends Controller
{   
    public function index()
    {   
        return Post::has('comments')->get();
    }
}

 

Now see the output:

[
    {
        "id": 1,
        "user_id": 1,
        "title": "Maxime non architecto quia in corporis iusto odio beatae. Harum cupiditate libero dicta et fuga vero. Autem facere id reprehenderit consectetur.",
        "is_published": 1,
        "created_at": "2023-01-15T04:59:18.000000Z",
        "updated_at": "2023-01-15T04:59:18.000000Z"
    }
]

 

Now see another example of retrieving all posts that have three or more comments. 

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\Post;

class TutorialController extends Controller
{   
    public function index()
    {   
        return Post::has('comments', '>=', 3)->get();
    }
}

 

We can check nested relationship existence like retrieving posts that have at least one comment with replies.:

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\Post;

class TutorialController extends Controller
{   
    public function index()
    {   
        return Post::has('comments.replies')->get();
    }
}

 

Read also: Laravel Nested Eager Loading With Condition

 

Conclusion

Now we know laravel query relationship existence. Hope this laravel where relationship has value tutorial will help you to create laravel where relation has value.