n Fetch results based on the existence of the relationship in Laravel | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

You can use Eloquent has() function to query relationships even two layers deep!

Example 1:

// Author -> hasMany(Book::class);
// Book -> hasMany(Rating::class);
$authors = Author::has('books.ratings')->get();

Example 2: Retrieve all posts that have at least one comment.

 $posts = App\Post::has('comments')->get();

 

Example 3: Retrieve all posts that have nbre of comments.

$posts = App\Post::has('comments', '>=', 3)->get();

 

Example 4: Retrieve posts that have at least one comment with votes.

$posts = App\Post::has('comments.votes')->get();

 

also you can use orHas() to make many conditions.

 

If you need even more power, you may use the whereHas and orWhereHas methods to put "where" conditions on your has queries.

Example 5: Retrieve posts with at least one comment containing words like "hello".

$posts = App\Post::whereHas('comments', function (Builder $query) {
    $query->where('content', 'like', '%hello%');
})->get();

 

Example 6: Retrieve posts with at least 3 comments containing words like "hello".


$posts = App\Post::whereHas('comments', function (Builder $query) {
    $query->where('content', 'like', '%hello%');
}, '>=', 3)->get();

 

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook