{"id":10867,"date":"2024-07-09T09:22:01","date_gmt":"2024-07-09T09:22:01","guid":{"rendered":"https:\/\/www.bacancytechnology.com\/qanda\/?p=10867"},"modified":"2024-07-09T09:22:01","modified_gmt":"2024-07-09T09:22:01","slug":"laravel-eloquent-has-with-wherehas","status":"publish","type":"post","link":"https:\/\/www.bacancytechnology.com\/qanda\/laravel\/laravel-eloquent-has-with-wherehas","title":{"rendered":"Laravel Eloquent: Understanding Has, With, and WhereHas"},"content":{"rendered":"<p>Laravel&#8217;s Eloquent ORM ( Object Relational mapping ) is a powerful tool for working with databases in our Laravel applications. It provides an intuitive interface for defining relationships between models and querying related data.<\/p>\n<p>In this blog post, we&#8217;ll dive deep into three important Eloquent methods: <strong>has(), with(), and whereHas()<\/strong>. We&#8217;ll explore what they mean, how they work, and when to use them, complete with practical examples.<\/p>\n<h3>The Has Method<\/h3>\n<p>The has() method is used to query for the existence of related models. It allows us to filter results based on the presence or absence of related records.<\/p>\n<p>When we use has()relation, we&#8217;re essentially asking, &#8220;Does this model have any related models in another table?&#8221;<\/p>\n<p>The has() method adds a where exists clause to your query. It checks for the existence of at least one related record that matches the given conditions.<\/p>\n<p>Lets understand it by diving into one of the example of use case of the has() clause,<\/p>\n<p>Say we have a Book model and a Review model, where a book can have multiple reviews.<br \/>\nNow, we want to find all books that have at least one review:<\/p>\n<p><code>$reviewedBooks = Book::has('reviews')-&gt;get();<\/code><\/p>\n<p>This query will return all <strong>books<\/strong> that have at least one <strong>associated<\/strong> review.<br \/>\nUsing above, we can also specify a <strong>minimum count<\/strong>.<\/p>\n<p><code>$popularBooks = Book::has('reviews', '&gt;=', 10)-&gt;get();<\/code><\/p>\n<p>This will return books that have 10 or more reviews.<\/p>\n<h3>The With Method<\/h3>\n<p>The with() method is used for eager loading related models. It helps optimize your queries by reducing the number of database queries needed to retrieve related data.<\/p>\n<p>When you use with(), we&#8217;re telling Eloquent That, &#8220;I know I&#8217;m going to need this related data, so please load it all at once.&#8221;<\/p>\n<p>The with() method performs a separate query to fetch the related models and then associates them with the main models in memory. This reduces the &#8220;<strong>N+1 query problem<\/strong>&#8221; where we might otherwise end up running a separate query for each related model.<\/p>\n<p>Let\u2019s understand it by diving into an Example,<\/p>\n<p>Say use an Author model that has many Book models:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\n$authorsWithBooks = Author::with('books')-&gt;get(); \r\nforeach ($authorsWithBooks as $author) {\r\n       echo $author-&gt;name . ' has written ' . $author-&gt;books-&gt;count() . ' books.';\r\n }<\/pre>\n<p>&nbsp;<br \/>\nThis will load all authors and their books in just two queries, rather than performing a separate query for each author&#8217;s books.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\n\/\/get all the Authors\r\nSelect * from authors\r\n\r\n\/\/Get The books based on Authors\r\nSelect * from books where authors.id IN (1,2,3,4,5,6.......)\r\n<\/pre>\n<h3>The WhereHas Method<\/h3>\n<p>The whereHas() and orWhereHas() method combines the functionality of has() with the ability to add custom constraints on the related models.<\/p>\n<p>When we use whereHas(), we&#8217;re asking, &#8220;Does this model have any related models that meet specific conditions?&#8221;<\/p>\n<p>The whereHas() method adds a where exists clause to our query, similar to has(), but allows us to specify additional conditions on the related models.<\/p>\n<p>Let\u2019s understanding it through an example, say we want to find all books that have received a 5-star review:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\n$highlyRatedBooks = Book::whereHas('reviews', function ($query) { \r\n      $query->where('rating', 5); \r\n})->get();\r\n<\/pre>\n<p>This query will return all books that have at least one review with a 5-star rating.<br \/>\nBased On above examples, we can combine all this methods to get a very powerful queries. <\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"php\">\r\n$books = Book::with('author') \r\n->whereHas('reviews', function ($query) { \r\n    $query->where('rating', '>=', 4); \r\n})\r\n ->has('categories') \r\n->get();\r\n<\/pre>\n<p><strong>This above query will results in following:<\/strong><\/p>\n<ol>\n<li>Eager load the author for each book<\/li>\n<li>Filter books to only those with reviews rated 4 or higher<\/li>\n<li>Further filter to only books that have been categorized<\/li>\n<li>Retrieve the resulting books with their authors<\/li>\n<\/ol>\n<h2>Conclusion<\/h2>\n<p>Understanding and effectively using has(), with(), and whereHas() in Laravel&#8217;s Eloquent ORM can significantly improve our  ability to write efficient and expressive database queries. By leveraging these methods, we can optimize our <strong>application&#8217;s performance and write cleaner, more maintainable code<\/strong>.<\/p>\n<h2>Key to Remember:<\/h2>\n<p>1.has(): Filters results based on the existence of related models, allowing you to quickly find records with (or without) specific relationships. <\/p>\n<p>2. with(): Implements eager loading, dramatically reducing the number of database queries and improving your application&#8217;s performance. <\/p>\n<p>3. whereHas(): Combines relationship checking with custom conditions, enabling complex, precise queries on related data.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Laravel&#8217;s Eloquent ORM ( Object Relational mapping ) is a powerful tool for working with databases in our Laravel applications. It provides an intuitive interface for defining relationships between models and querying related data. In this blog post, we&#8217;ll dive deep into three important Eloquent methods: has(), with(), and whereHas(). We&#8217;ll explore what they mean, [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":10868,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[10],"tags":[],"class_list":["post-10867","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-laravel"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/10867"}],"collection":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/comments?post=10867"}],"version-history":[{"count":2,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/10867\/revisions"}],"predecessor-version":[{"id":10870,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/10867\/revisions\/10870"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media\/10868"}],"wp:attachment":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media?parent=10867"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/categories?post=10867"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/tags?post=10867"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}