• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
Tutsplanet

Tutsplanet

Free Technical and Blogging Resources

  • Home
  • Web Hosting
  • Programming
  • Plugins
  • Twitter Trends
  • Tools
  • About Us

Programming TagsLaravel

Laravel WhereHas() Eloquent Example

Aug 29, 2021 Editorial Staff Leave a Comment

Share
Tweet
Share
3 Shares

WhereHas() is a Laravel eloquent method, which helps to define additional query constraints on your queries, such as filtering your books with some author name. For example, return all the books if it matches an author named Charles Dickens. But whereHas() often confused with some other terms in Laravel, has() and with(), which is very confusing for new developers.

Before we start with the whereHas, we will go through the with() and has() methods.
First of all, we examine with()  method,:

with()

The related models are lazy-loaded when accessing eloquent relationships as properties. It means the actual relationship data is not loaded until you call the property. So Laravel with() method helps to eager load values. What this means is, along with the main model, Laravel preloads the relationships, which results in fewer database queries.

In the event of multiple models, and you need to load them at once, this method is really efficient, and it reduces the database interaction as it calls the database only once. With eager loading, you run only one additional database query instead of one for every model in the collection.

Example

$posts = Post::with('comments')->get();
foreach($posts as $post){
    $post->comments; 
}

Comments are already loaded and no additional DB query is run

has()

Let’s say we have posts and comments, with a 1-n relationship, and one Post can have many comments.
So our Post model will look like below

public function comments(){
    return $this->hasMany(\App\Models\Comment::class, 'post_id');
}

Think, what if we want to show only posts with at least one comment. Here comes our has() method to rescue.

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

whereHas()

So we are back to our original Topic, ie whereHas() method. So it works almost the same as has() method, but it allows you have additional conditions on the related models.

$posts = Post::whereHas('comments', function($q){
    $q->where('status', '=', 'active');
})->get();
// only posts that have comments that is active will be returned

Example usage of whereHas() with with()

$posts = Post::whereHas('comments', function ($query) {
        $query->where('content', 'like', 'foo%');
})->with(['comments' => function ($query) {
        $query->where('content', 'like', 'foo%');
}])->get();

Also, this can be rewritten like the below, which is much cleaner and avoiding code duplication.

$callback = function($query) {
    $query->where('something', '=', 'something');
}

$posts = Post::whereHas('comments', $callback)->with(['comments' => $callback])->get();

Editorial Staff

Editorial Staff at Tutsplanet is a dedicated team to write various tutorials about subjects like Programming, Technology and Operating Systems.

View all posts by Editorial Staff

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Quick Links

  • Top 21 Website Ideas To Make Money Online in 2021
  • A Simple YouTube Video Downloader Script in PHP
  • The 50 Most Useful jQuery Plugins for Frontend Development
  • Replace “\n” with new line characters, using Notepad++
  • Using Third-Party Libraries in Codeigniter
  • Upload Multiple Images and Store in Database using PHP and MySQL.
  • Hierarchical Tree view Category Example in Laravel
  • Laravel Image Intervention Tutorial With Example
  • How to import sql file in MySQL database using PHP?
  • Free VAT Calculator Online

Subscribe

* indicates required



Search Here

Share

   



Hot topics

  • Replace “\n” with new line characters, using Notepad++ 14 views
  • Solution: windows photo viewer opens each time save a pic file 12 views
  • Simple PHP Shopping Cart 10 views
  • A Simple YouTube Video Downloader Script in PHP 10 views
  • How to Create PDF File From HTML Form Using Fpdf? 9 views
  • All Countries SQL file with Country Codes to Download 8 views
  • How to create and download a Zip file with PHP 8 views
  • How to set up GitHub SSH in Ubuntu with example 7 views
  • How to enter new line in Microsoft Teams? 7 views
  • Laravel Eloquent Select Column as Alias 7 views

Categories

  • Design & Development
  • Drupal
  • Facebook
  • General
  • How To
  • ios
  • Javascript
  • Linux
  • Magento
  • Marketing
  • News
  • PHP
  • Plugins
  • Programming
  • Snippets List
  • Social Media
  • Softwares
  • Themes
  • Tips
  • Wordpress
  • YouTube























Copyright © 2023 · Planet on Genesis Framework · Powered By BunnyCDN . Network wallpapernoon.com