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();

 

Comments

Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon