{"id":1130,"date":"2023-08-29T05:12:50","date_gmt":"2023-08-29T05:12:50","guid":{"rendered":"https:\/\/www.w3computing.com\/articles\/?p=1130"},"modified":"2023-08-29T05:27:57","modified_gmt":"2023-08-29T05:27:57","slug":"advanced-laravel-eloquent-techniques","status":"publish","type":"post","link":"https:\/\/www.w3computing.com\/articles\/advanced-laravel-eloquent-techniques\/","title":{"rendered":"Advanced Laravel Eloquent Techniques"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">Introduction<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Eloquent is an Object-Relational Mapping (ORM) included with Laravel, one of the most popular PHP frameworks. It provides a beautiful, simple ActiveRecord implementation for working with your database. With Eloquent, you can manage complex database interactions using a more expressive and more maintainable syntax. Gone are the days of writing raw SQL queries; with Eloquent, your models are your gateway to all things database-related, be it basic CRUD operations, or more advanced tasks like eager-loading, polymorphic relations, and more.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This tutorial assumes that you are not a beginner to Laravel or Eloquent. You should already be familiar with creating models, defining relationships, and basic query-building techniques. If you are new to Eloquent or Laravel, you might find this tutorial challenging to follow. For the seasoned developers, buckle up, as we delve deep into the intricacies and advanced functionalities Eloquent has to offer.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this comprehensive tutorial, we will explore the depths of advanced Eloquent techniques, such as:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Model Scopes: How to create reusable query constraints<\/li>\n\n\n\n<li>Eager Loading Techniques: Efficiently loading relational data<\/li>\n\n\n\n<li>Polymorphic Relationships: Making models more versatile<\/li>\n\n\n\n<li>Dynamic Queries: How to build queries on-the-fly<\/li>\n\n\n\n<li>Custom Accessors and Mutators: Transforming attribute values when retrieving or setting them<\/li>\n\n\n\n<li>Pivot Tables and Many-to-Many Relationships: Handling complex data relationships effortlessly<\/li>\n\n\n\n<li>Optimizing Eloquent for Performance: Making your queries run faster<\/li>\n\n\n\n<li>Query Debugging Techniques: Understanding what\u2019s happening behind the scenes<\/li>\n\n\n\n<li>Testing Eloquent Models: Writing tests to ensure your Eloquent logic is solid<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Importance of Mastering Advanced Eloquent Techniques for Laravel Development<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Mastering advanced Eloquent techniques is not just an academic exercise; it&#8217;s a necessity for any serious Laravel developer. With more complex projects, you&#8217;ll find the need to write optimized, reusable, and maintainable database queries, which is exactly where advanced Eloquent skills shine. You&#8217;ll be able to:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Write cleaner, more expressive code<\/li>\n\n\n\n<li>Optimize the performance of your applications<\/li>\n\n\n\n<li>Build more complex and robust systems<\/li>\n\n\n\n<li>Troubleshoot and debug issues faster<\/li>\n\n\n\n<li>Collaborate more efficiently with other team members by using universally understood Eloquent techniques<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">By the end of this tutorial, you&#8217;ll gain a toolkit of techniques to help you build more robust, maintainable, and optimized Laravel applications.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Before diving into the complexities of advanced Eloquent techniques, it&#8217;s essential to establish some ground rules and prerequisites. This will ensure that you have the necessary background and tools to fully benefit from this tutorial.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Knowledge in Laravel and Basic Eloquent Functionality<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">You should have a solid understanding of the Laravel framework, including but not limited to:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Routing, controllers, and views<\/li>\n\n\n\n<li>Basic middleware functionality<\/li>\n\n\n\n<li>Blade templating engine<\/li>\n\n\n\n<li>Dependency injection and service providers<\/li>\n\n\n\n<li>Composer for dependency management<\/li>\n\n\n\n<li><strong>Most importantly<\/strong>, a firm grasp of basic Eloquent operations like CRUD (Create, Read, Update, Delete), and understanding relationships like One-to-One, One-to-Many, and Many-to-Many.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">This tutorial will not cover these foundational elements. We&#8217;ll assume that you&#8217;re already comfortable with them, as we explore more specialized, higher-level topics.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Tools Required<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To follow along with this tutorial, you&#8217;ll need the following tools and environment setup:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Laravel Setup<\/strong>: A fresh or existing Laravel project where you can test and run the code examples. You should be using a version of Laravel that is up-to-date with the latest features for the best experience.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>IDE (Integrated Development Environment)<\/strong>: Although not strictly necessary, an IDE like PHPStorm, Visual Studio Code, or Sublime Text can greatly enhance your coding experience, providing useful features like code suggestions, linting, and debugging tools.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Database<\/strong>: MySQL, PostgreSQL, SQLite, or any other database system supported by Laravel. Make sure it is installed and configured, as we&#8217;ll be running various database queries.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Terminal<\/strong>: You&#8217;ll need a command-line interface (CLI) to run Artisan commands, Composer commands, and more.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Version Control (Optional)<\/strong>: It&#8217;s a good practice to use a version control system like Git to track your changes, especially when experimenting with advanced techniques.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Model Scopes<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In Eloquent, scopes offer you a way to reuse query logic in your models. Instead of repeating the same <code>where<\/code> clauses in each query, you can define a method on your Eloquent model that encapsulates that query logic for easy reuse. There are two types of scopes in Eloquent: local and global scopes. In this section, we&#8217;ll focus on global scopes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Global Scopes<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Explanation and Use Case<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">A global scope is a query constraint that is automatically added to every Eloquent query for a given model. This means that every retrieval and manipulation made via Eloquent models will be affected by this constraint, making it ideal for cross-cutting concerns like soft-deleting records, filtering data based on logged-in users, or applying multi-tenancy logic.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, let&#8217;s say you&#8217;re building a blogging platform and you want to ensure that only published posts should be retrieved from the <code>posts<\/code> table by default. This is where a global scope could be incredibly useful.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">To define a global scope, you&#8217;ll typically create a new class that implements Laravel&#8217;s <code>Scope<\/code> interface. This interface requires you to implement one method: <code>apply<\/code>. The <code>apply<\/code> method receives the Eloquent query builder instance and the Eloquent model as its arguments.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s how you can define a global scope for only retrieving published posts.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">First, create the global scope class.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">\/\/ app\/Scopes\/PublishedScope.php<\/span>\r\n\r\n<span class=\"hljs-keyword\">namespace<\/span> <span class=\"hljs-title\">App<\/span>\\<span class=\"hljs-title\">Scopes<\/span>;\r\n\r\n<span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">Illuminate<\/span>\\<span class=\"hljs-title\">Database<\/span>\\<span class=\"hljs-title\">Eloquent<\/span>\\<span class=\"hljs-title\">Builder<\/span>;\r\n<span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">Illuminate<\/span>\\<span class=\"hljs-title\">Database<\/span>\\<span class=\"hljs-title\">Eloquent<\/span>\\<span class=\"hljs-title\">Model<\/span>;\r\n<span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">Illuminate<\/span>\\<span class=\"hljs-title\">Database<\/span>\\<span class=\"hljs-title\">Eloquent<\/span>\\<span class=\"hljs-title\">Scope<\/span>;\r\n\r\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">PublishedScope<\/span> <span class=\"hljs-keyword\">implements<\/span> <span class=\"hljs-title\">Scope<\/span>\r\n<\/span>{\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">apply<\/span><span class=\"hljs-params\">(Builder $builder, Model $model)<\/span>\r\n    <\/span>{\r\n        $builder-&gt;where(<span class=\"hljs-string\">'status'<\/span>, <span class=\"hljs-string\">'published'<\/span>);\r\n    }\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Next, you can apply the global scope to your model using the <code>addGlobalScope<\/code> method in its constructor.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">\/\/ app\/Models\/Post.php<\/span>\r\n\r\n<span class=\"hljs-keyword\">namespace<\/span> <span class=\"hljs-title\">App<\/span>\\<span class=\"hljs-title\">Models<\/span>;\r\n\r\n<span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">Illuminate<\/span>\\<span class=\"hljs-title\">Database<\/span>\\<span class=\"hljs-title\">Eloquent<\/span>\\<span class=\"hljs-title\">Model<\/span>;\r\n<span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">App<\/span>\\<span class=\"hljs-title\">Scopes<\/span>\\<span class=\"hljs-title\">PublishedScope<\/span>;\r\n\r\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Post<\/span> <span class=\"hljs-keyword\">extends<\/span> <span class=\"hljs-title\">Model<\/span>\r\n<\/span>{\r\n    <span class=\"hljs-keyword\">protected<\/span> $table = <span class=\"hljs-string\">'posts'<\/span>;\r\n\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">__construct<\/span><span class=\"hljs-params\">(array $attributes = &#91;])<\/span>\r\n    <\/span>{\r\n        <span class=\"hljs-keyword\">parent<\/span>::__construct($attributes);\r\n        <span class=\"hljs-keyword\">$this<\/span>-&gt;addGlobalScope(<span class=\"hljs-keyword\">new<\/span> PublishedScope);\r\n    }\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Now, every query made via the <code>Post<\/code> model will automatically include a constraint to only retrieve posts that are published.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">\/\/ Automatically applies 'where status = published'<\/span>\r\n$posts = Post::all(); \r\n\r\n<span class=\"hljs-comment\">\/\/ Automatically applies 'where status = published' in the background<\/span>\r\n$singlePost = Post::find(<span class=\"hljs-number\">1<\/span>);\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">To remove the global scope for a specific query, you can use the <code>withoutGlobalScope<\/code> method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">\/\/ This query will not include the global scope constraint<\/span>\r\n$posts = Post::withoutGlobalScope(PublishedScope::class)-&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">And there you have it! A simple yet powerful way to define and use global scopes to encapsulate and reuse query logic in your Laravel applications.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Local Scopes<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Explanation and Use Case<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Local scopes allow you to define common sets of query constraints that you can reuse conveniently. Unlike global scopes, which are automatically applied to all queries on a model, local scopes are applied only when you explicitly call them in query construction. This makes them highly useful for conditional or optional query constraints.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s consider an example: Imagine you have a <code>users<\/code> table, and you often need to filter users based on their account status (e.g., active, suspended, or archived). Instead of repeatedly writing the same <code>where<\/code> clauses for each query, you could define a local scope for each of these conditions.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Defining a local scope involves adding a method to your Eloquent model. The method&#8217;s name should be prefixed with <code>scope<\/code>, and you&#8217;ll provide the logic within it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s how you can define local scopes for filtering users based on their account status:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">\/\/ app\/Models\/User.php<\/span>\r\n\r\n<span class=\"hljs-keyword\">namespace<\/span> <span class=\"hljs-title\">App<\/span>\\<span class=\"hljs-title\">Models<\/span>;\r\n\r\n<span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">Illuminate<\/span>\\<span class=\"hljs-title\">Database<\/span>\\<span class=\"hljs-title\">Eloquent<\/span>\\<span class=\"hljs-title\">Model<\/span>;\r\n\r\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">User<\/span> <span class=\"hljs-keyword\">extends<\/span> <span class=\"hljs-title\">Model<\/span>\r\n<\/span>{\r\n    <span class=\"hljs-comment\">\/\/ Local scope for active users<\/span>\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">scopeActive<\/span><span class=\"hljs-params\">($query)<\/span>\r\n    <\/span>{\r\n        <span class=\"hljs-keyword\">return<\/span> $query-&gt;where(<span class=\"hljs-string\">'account_status'<\/span>, <span class=\"hljs-string\">'active'<\/span>);\r\n    }\r\n\r\n    <span class=\"hljs-comment\">\/\/ Local scope for suspended users<\/span>\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">scopeSuspended<\/span><span class=\"hljs-params\">($query)<\/span>\r\n    <\/span>{\r\n        <span class=\"hljs-keyword\">return<\/span> $query-&gt;where(<span class=\"hljs-string\">'account_status'<\/span>, <span class=\"hljs-string\">'suspended'<\/span>);\r\n    }\r\n\r\n    <span class=\"hljs-comment\">\/\/ Local scope for archived users<\/span>\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">scopeArchived<\/span><span class=\"hljs-params\">($query)<\/span>\r\n    <\/span>{\r\n        <span class=\"hljs-keyword\">return<\/span> $query-&gt;where(<span class=\"hljs-string\">'account_status'<\/span>, <span class=\"hljs-string\">'archived'<\/span>);\r\n    }\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">You can apply these local scopes while constructing a query by calling the scope methods without the <code>scope<\/code> prefix and in camelCase format:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">\/\/ Retrieve all active users<\/span>\r\n$activeUsers = User::active()-&gt;get();\r\n\r\n<span class=\"hljs-comment\">\/\/ Retrieve all suspended users<\/span>\r\n$suspendedUsers = User::suspended()-&gt;get();\r\n\r\n<span class=\"hljs-comment\">\/\/ Retrieve all archived users<\/span>\r\n$archivedUsers = User::archived()-&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\">Chaining Local Scopes<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">One of the benefits of local scopes is that you can chain them together with other query methods for more complex queries.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">\/\/ Retrieve all active users, sorted by their name<\/span>\r\n$activeUsers = User::active()-&gt;orderBy(<span class=\"hljs-string\">'name'<\/span>)-&gt;get();\r\n\r\n<span class=\"hljs-comment\">\/\/ Retrieve all suspended users with a specific role<\/span>\r\n$suspendedUsers = User::suspended()-&gt;where(<span class=\"hljs-string\">'role'<\/span>, <span class=\"hljs-string\">'admin'<\/span>)-&gt;get();\r\n\r\n<span class=\"hljs-comment\">\/\/ Retrieve archived users who have been updated in the last 30 days<\/span>\r\n$recentArchivedUsers = User::archived()-&gt;where(<span class=\"hljs-string\">'updated_at'<\/span>, <span class=\"hljs-string\">'&gt;='<\/span>, now()-&gt;subDays(<span class=\"hljs-number\">30<\/span>))-&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\">Removing Global Scopes<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">How and When to Remove a Global Scope<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Global scopes are useful for adding constraints that should be universally applied to all queries for a given model. However, there will inevitably be situations where you need to execute queries without these constraints. Thankfully, Eloquent provides a straightforward way to remove global scopes from your queries, either temporarily or permanently.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">When to Remove a Global Scope<\/h5>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Testing Scenarios<\/strong>: During unit tests or feature tests, you might need to bypass the global scope to verify the functionality of your application.<\/li>\n\n\n\n<li><strong>Admin Features<\/strong>: If you are developing an admin interface, you might need to show records irrespective of the global constraints applied by global scopes.<\/li>\n\n\n\n<li><strong>Conditional Logic<\/strong>: Sometimes, the business logic requires a selective bypass of global constraints based on user roles, tasks, or other conditions.<\/li>\n\n\n\n<li><strong>Debugging<\/strong>: While diagnosing an issue, it might be helpful to rule out global scopes as the root cause by temporarily removing them from the query.<\/li>\n<\/ol>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Continuing with our blogging example, suppose you have a global scope that only fetches posts with a <code>published<\/code> status. Now, let&#8217;s say you are building an admin interface where you need to show all posts, regardless of their status. Here&#8217;s how to remove that global scope.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">Removing a Single Global Scope<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">To remove a single global scope, you can use the <code>withoutGlobalScope<\/code> method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">App<\/span>\\<span class=\"hljs-title\">Scopes<\/span>\\<span class=\"hljs-title\">PublishedScope<\/span>;\r\n\r\n<span class=\"hljs-comment\">\/\/ This query will not include the 'published' global scope<\/span>\r\n$allPosts = \\App\\Models\\Post::withoutGlobalScope(PublishedScope::class)-&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Removing Multiple Global Scopes<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">If you need to remove multiple global scopes, you can chain <code>withoutGlobalScope<\/code> methods:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">\/\/ This query will not include the 'published' and some other global scope<\/span>\r\n$allPosts = \\App\\Models\\Post::withoutGlobalScope(PublishedScope::class)\r\n                            -&gt;withoutGlobalScope(AnotherGlobalScope::class)\r\n                            -&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Removing All Global Scopes<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">To remove all global scopes from the query, you can use <code>withoutGlobalScopes<\/code>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-10\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">\/\/ This query will not include any global scopes<\/span>\r\n$allPosts = \\App\\Models\\Post::withoutGlobalScopes()-&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-10\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Removing Global Scopes for a Specific Instance<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">You can also remove global scopes for a specific model instance:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-11\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$post = <span class=\"hljs-keyword\">new<\/span> \\App\\Models\\Post;\r\n$post-&gt;withoutGlobalScope(PublishedScope::class)-&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-11\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Eager Loading Techniques<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Eager loading is a crucial concept in Laravel&#8217;s Eloquent ORM that helps to optimize your application&#8217;s performance by reducing the number of queries needed when working with model relationships. By loading all related data in a single query upfront, you can eliminate the N+1 query problem, making your application more efficient and your code cleaner.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Basic Eager Loading<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Explanation and Use Case<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">In a Laravel application, it&#8217;s common to have relationships between models, like a <code>User<\/code> having multiple <code>Post<\/code>s. If you need to display the posts alongside the user information, doing it in a naive way might lead to an N+1 query problem. This problem occurs when you fetch a model and its related models via a loop, which results in multiple queries and poor performance.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Eager loading solves this problem by fetching the related models in a single query. This is particularly useful in scenarios where you need to retrieve a model alongside its related models.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, if you&#8217;re building a blog and you want to display all posts along with their author&#8217;s information, eager loading can drastically reduce the number of queries made to the database.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s start by looking at the N+1 problem:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-12\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">\/\/ This will result in N+1 problem<\/span>\r\n$posts = \\App\\Models\\Post::all();\r\n\r\n<span class=\"hljs-keyword\">foreach<\/span> ($posts <span class=\"hljs-keyword\">as<\/span> $post) {\r\n    <span class=\"hljs-keyword\">echo<\/span> $post-&gt;author-&gt;name;\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-12\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">For each iteration of the loop, an additional query is executed to fetch the <code>author<\/code> information, leading to N+1 queries in total.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now, let&#8217;s solve it with basic eager loading:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-13\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">\/\/ Using Eager Loading to solve N+1 problem<\/span>\r\n$posts = \\App\\Models\\Post::with(<span class=\"hljs-string\">'author'<\/span>)-&gt;get();\r\n\r\n<span class=\"hljs-keyword\">foreach<\/span> ($posts <span class=\"hljs-keyword\">as<\/span> $post) {\r\n    <span class=\"hljs-keyword\">echo<\/span> $post-&gt;author-&gt;name;\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-13\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In this example, the <code>with('author')<\/code> method tells Eloquent to &#8220;eager load&#8221; the <code>author<\/code> relationship. Now, instead of executing N+1 queries, Eloquent executes just two queries:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>One query to retrieve all posts.<\/li>\n\n\n\n<li>Another query to retrieve all authors related to the retrieved posts.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>author<\/code> models are then &#8220;matched&#8221; back to their parent <code>Post<\/code> models, allowing you to efficiently access the <code>author<\/code> data without additional queries.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Conditional Eager Loading<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Explanation and Use Case<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Conditional eager loading allows you to load a relationship only if a condition is met, giving you more granular control over the queries being executed. This becomes useful when you need to apply certain constraints to the eagerly loaded models or if you want to decide at runtime whether to eager load a relation based on some conditions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For instance, consider a blog platform where posts can have comments, and you only want to load the comments that are approved by moderators. Or perhaps you have an e-commerce platform, and you want to load the product reviews only for the products that are currently on sale.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example<\/h4>\n\n\n\n<h5 class=\"wp-block-heading\">Conditional Eager Loading Based on an Attribute<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Suppose you have a <code>Post<\/code> model and each <code>Post<\/code> can have multiple <code>Comment<\/code>s. You want to load comments only for posts that are published. You can use the <code>with<\/code> method and pass a closure to it, like so:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-14\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$posts = \\App\\Models\\Post::with(&#91;<span class=\"hljs-string\">'comments'<\/span> =&gt; <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">($query)<\/span> <\/span>{\r\n    $query-&gt;where(<span class=\"hljs-string\">'status'<\/span>, <span class=\"hljs-string\">'approved'<\/span>);\r\n}])-&gt;where(<span class=\"hljs-string\">'status'<\/span>, <span class=\"hljs-string\">'published'<\/span>)-&gt;get();\r\n\r\n<span class=\"hljs-keyword\">foreach<\/span> ($posts <span class=\"hljs-keyword\">as<\/span> $post) {\r\n    <span class=\"hljs-comment\">\/\/ This will only load comments that have a 'status' of 'approved'<\/span>\r\n    $comments = $post-&gt;comments;\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-14\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Dynamic Conditional Eager Loading<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">In some cases, you may want to decide whether to load a relationship based on runtime conditions. For this, you can use the <code>load<\/code> method conditionally:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-15\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$posts = \\App\\Models\\Post::all();\r\n\r\n<span class=\"hljs-keyword\">if<\/span> ($someCondition) {\r\n    $posts-&gt;load(<span class=\"hljs-string\">'comments'<\/span>);\r\n}\r\n\r\n<span class=\"hljs-keyword\">foreach<\/span> ($posts <span class=\"hljs-keyword\">as<\/span> $post) {\r\n    <span class=\"hljs-comment\">\/\/ Comments will be loaded only if $someCondition is true<\/span>\r\n    $comments = $post-&gt;comments;\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-15\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Eager Loading Multiple Conditions<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">You can also combine multiple conditions when eager loading relationships:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-16\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$posts = \\App\\Models\\Post::with(&#91;\r\n    <span class=\"hljs-string\">'comments'<\/span> =&gt; <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">($query)<\/span> <\/span>{\r\n        $query-&gt;where(<span class=\"hljs-string\">'status'<\/span>, <span class=\"hljs-string\">'approved'<\/span>);\r\n    },\r\n    <span class=\"hljs-string\">'author'<\/span> =&gt; <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">($query)<\/span> <\/span>{\r\n        $query-&gt;select(<span class=\"hljs-string\">'id'<\/span>, <span class=\"hljs-string\">'name'<\/span>);\r\n    }\r\n])-&gt;where(<span class=\"hljs-string\">'status'<\/span>, <span class=\"hljs-string\">'published'<\/span>)-&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-16\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In this example, we load <code>comments<\/code> where the status is &#8216;approved&#8217; and also load the <code>author<\/code> information, but only the <code>id<\/code> and <code>name<\/code> columns.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Eager Loading with Constraints<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Explanation and Use Case<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Eager loading with constraints extends the power of Eloquent&#8217;s eager loading feature by allowing you to apply additional query constraints to the eagerly-loaded models. This provides an efficient way to filter or sort related models when you&#8217;re eager loading them, thus reducing the amount of post-query data manipulation you&#8217;ll need to do.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, let&#8217;s assume you&#8217;re building an e-commerce platform and have a <code>Product<\/code> model that has many <code>Review<\/code>s. You might want to load only the reviews with a rating of 4 or higher. Alternatively, consider a blog platform where posts can have tags, and you only want to load tags that are &#8216;active&#8217;.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example<\/h4>\n\n\n\n<h5 class=\"wp-block-heading\">Eager Loading with <code>where<\/code> Constraints<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s look at how you can eager load comments on posts, but only if those comments have been approved.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-17\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$posts = \\App\\Models\\Post::with(&#91;<span class=\"hljs-string\">'comments'<\/span> =&gt; <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">($query)<\/span> <\/span>{\r\n    $query-&gt;where(<span class=\"hljs-string\">'is_approved'<\/span>, <span class=\"hljs-keyword\">true<\/span>);\r\n}])-&gt;get();\r\n\r\n<span class=\"hljs-keyword\">foreach<\/span> ($posts <span class=\"hljs-keyword\">as<\/span> $post) {\r\n    <span class=\"hljs-comment\">\/\/ This will only load comments that are approved<\/span>\r\n    $comments = $post-&gt;comments;\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-17\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In this example, the closure passed to the <code>with<\/code> method adds a <code>where<\/code> constraint to the <code>comments<\/code> relation, loading only those comments that have been approved (<code>is_approved<\/code> is true).<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">Eager Loading with Sorting<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Suppose you want to sort those approved comments by their creation date:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-18\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$posts = \\App\\Models\\Post::with(&#91;<span class=\"hljs-string\">'comments'<\/span> =&gt; <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">($query)<\/span> <\/span>{\r\n    $query-&gt;where(<span class=\"hljs-string\">'is_approved'<\/span>, <span class=\"hljs-keyword\">true<\/span>)\r\n          -&gt;orderBy(<span class=\"hljs-string\">'created_at'<\/span>, <span class=\"hljs-string\">'desc'<\/span>);\r\n}])-&gt;get();\r\n\r\n<span class=\"hljs-keyword\">foreach<\/span> ($posts <span class=\"hljs-keyword\">as<\/span> $post) {\r\n    <span class=\"hljs-comment\">\/\/ This will load comments that are approved and sort them by 'created_at' in descending order<\/span>\r\n    $comments = $post-&gt;comments;\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-18\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Eager Loading with Selective Columns<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Sometimes, you might want to select only a subset of columns for the related models to reduce the amount of data being loaded:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-19\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$posts = \\App\\Models\\Post::with(&#91;<span class=\"hljs-string\">'comments'<\/span> =&gt; <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">($query)<\/span> <\/span>{\r\n    $query-&gt;select(<span class=\"hljs-string\">'id'<\/span>, <span class=\"hljs-string\">'post_id'<\/span>, <span class=\"hljs-string\">'content'<\/span>)\r\n          -&gt;where(<span class=\"hljs-string\">'is_approved'<\/span>, <span class=\"hljs-keyword\">true<\/span>);\r\n}])-&gt;get();\r\n\r\n<span class=\"hljs-keyword\">foreach<\/span> ($posts <span class=\"hljs-keyword\">as<\/span> $post) {\r\n    <span class=\"hljs-comment\">\/\/ This will load comments that are approved and only select the 'id', 'post_id', and 'content' columns<\/span>\r\n    $comments = $post-&gt;comments;\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-19\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h1 class=\"wp-block-heading\">Polymorphic Relationships<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Polymorphic relationships in Laravel&#8217;s Eloquent allow a model to belong to more than one type of model on a single association. This can be incredibly useful for keeping your database schema clean and making the system more maintainable. This flexibility can be beneficial in various scenarios, like when you have multiple models that need to be associated with another model, but you don&#8217;t want to create multiple tables for each association.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">One-to-One Polymorphic Relationships<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation and Use Case<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A one-to-one polymorphic relation is best described by an example: imagine you&#8217;re building a content management system where <code>Articles<\/code>, <code>Videos<\/code>, and <code>Podcasts<\/code> can all have a <code>Comment<\/code>. Instead of having separate tables linking <code>Comment<\/code> to each type of content, we can use a one-to-one polymorphic relationship to allow <code>Comment<\/code> to be associated with either an <code>Article<\/code>, <code>Video<\/code>, or <code>Podcast<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Code Example<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">First, let&#8217;s set up the models. The <code>Comment<\/code> model needs two additional fields: <code>commentable_id<\/code> and <code>commentable_type<\/code>. These will be used to store the ID and the type of the related model.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In the <code>Comment<\/code> model:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-20\" data-shcb-language-name=\"MoonScript\" data-shcb-language-slug=\"moonscript\"><span><code class=\"hljs language-moonscript\">namespace App\\Models;\r\n\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\n\r\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Comment<\/span> <span class=\"hljs-keyword\">extends<\/span> <span class=\"hljs-title\">Model<\/span><\/span>\r\n{\r\n    public function commentable()\r\n    {\r\n        <span class=\"hljs-keyword\">return<\/span> $this-&gt;morphTo();\r\n    }\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-20\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">MoonScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">moonscript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In the <code>Article<\/code>, <code>Video<\/code>, and <code>Podcast<\/code> models:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-21\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-keyword\">namespace<\/span> <span class=\"hljs-title\">App<\/span>\\<span class=\"hljs-title\">Models<\/span>;\r\n\r\n<span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">Illuminate<\/span>\\<span class=\"hljs-title\">Database<\/span>\\<span class=\"hljs-title\">Eloquent<\/span>\\<span class=\"hljs-title\">Model<\/span>;\r\n\r\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Article<\/span> <span class=\"hljs-keyword\">extends<\/span> <span class=\"hljs-title\">Model<\/span>\r\n<\/span>{\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">comment<\/span><span class=\"hljs-params\">()<\/span>\r\n    <\/span>{\r\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">$this<\/span>-&gt;morphOne(Comment::class, <span class=\"hljs-string\">'commentable'<\/span>);\r\n    }\r\n}\r\n\r\n<span class=\"hljs-comment\">\/\/ Similarly, for Video and Podcast<\/span>\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-21\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Database Migrations<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For <code>comments<\/code> table, you would create a migration something like:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-22\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">Schema::create(<span class=\"hljs-string\">'comments'<\/span>, <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">(Blueprint $table)<\/span> <\/span>{\r\n    $table-&gt;id();\r\n    $table-&gt;text(<span class=\"hljs-string\">'body'<\/span>);\r\n    $table-&gt;unsignedBigInteger(<span class=\"hljs-string\">'commentable_id'<\/span>);\r\n    $table-&gt;string(<span class=\"hljs-string\">'commentable_type'<\/span>);\r\n    $table-&gt;timestamps();\r\n});\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-22\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Storing Comments<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s how you can store a comment for an article:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-23\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$article = \\App\\Models\\Article::find(<span class=\"hljs-number\">1<\/span>);\r\n$comment = <span class=\"hljs-keyword\">new<\/span> \\App\\Models\\Comment(&#91;<span class=\"hljs-string\">'body'<\/span> =&gt; <span class=\"hljs-string\">'A comment.'<\/span>]);\r\n$article-&gt;comment()-&gt;save($comment);\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-23\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Retrieving Comments<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To retrieve the comment associated with an article:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-24\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$comment = \\App\\Models\\Article::find(<span class=\"hljs-number\">1<\/span>)-&gt;comment;\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-24\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">You can do the same for <code>Video<\/code> and <code>Podcast<\/code> models.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By using one-to-one polymorphic relationships, you&#8217;ve achieved a more maintainable and scalable database design, allowing different models to share the same kind of relationship without needing multiple tables to store them.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Many-to-Many Polymorphic Relationships<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">While one-to-one polymorphic relationships are useful for associating one record with another, many-to-many polymorphic relationships take this a step further by allowing you to associate many records from a model to many records of another (or the same) model. This can be useful in situations where you have multiple entities that need to be related in a many-to-many fashion to another entity.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Explanation and Use Case<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Suppose you&#8217;re building a social media platform where users can &#8220;like&#8221; multiple types of content\u2014be it <code>Posts<\/code>, <code>Photos<\/code>, or <code>Comments<\/code>. Instead of creating multiple pivot tables for each type (e.g., <code>user_post_likes<\/code>, <code>user_photo_likes<\/code>, <code>user_comment_likes<\/code>), you can create a single pivot table (e.g., <code>likes<\/code>) to handle these relationships.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>likes<\/code> table would contain columns for the <code>user_id<\/code>, the <code>likable_id<\/code>, and the <code>likable_type<\/code> (e.g., <code>Post<\/code>, <code>Photo<\/code>, <code>Comment<\/code>). The <code>likable_id<\/code> and <code>likable_type<\/code> fields will indicate what type of model is being liked.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s set up our models first.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">The <code>Like<\/code> Model<\/h5>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-25\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-keyword\">namespace<\/span> <span class=\"hljs-title\">App<\/span>\\<span class=\"hljs-title\">Models<\/span>;\r\n\r\n<span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">Illuminate<\/span>\\<span class=\"hljs-title\">Database<\/span>\\<span class=\"hljs-title\">Eloquent<\/span>\\<span class=\"hljs-title\">Model<\/span>;\r\n\r\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Like<\/span> <span class=\"hljs-keyword\">extends<\/span> <span class=\"hljs-title\">Model<\/span>\r\n<\/span>{\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">likable<\/span><span class=\"hljs-params\">()<\/span>\r\n    <\/span>{\r\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">$this<\/span>-&gt;morphTo();\r\n    }\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-25\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">The <code>User<\/code> Model<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">In the <code>User<\/code> model, add a <code>likes<\/code> method to specify the polymorphic relation:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-26\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">likes<\/span><span class=\"hljs-params\">()<\/span>\r\n<\/span>{\r\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">$this<\/span>-&gt;morphedByMany(Like::class, <span class=\"hljs-string\">'likable'<\/span>);\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-26\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">The <code>Post<\/code>, <code>Photo<\/code>, and <code>Comment<\/code> Models<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">In each of these models, you would add a method to define the inverse relation:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-27\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">likes<\/span><span class=\"hljs-params\">()<\/span>\r\n<\/span>{\r\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">$this<\/span>-&gt;morphToMany(User::class, <span class=\"hljs-string\">'likable'<\/span>);\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-27\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Database Migrations<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">For the <code>likes<\/code> table, your migration might look like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-28\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">Schema::create(<span class=\"hljs-string\">'likes'<\/span>, <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">(Blueprint $table)<\/span> <\/span>{\r\n    $table-&gt;id();\r\n    $table-&gt;unsignedBigInteger(<span class=\"hljs-string\">'user_id'<\/span>);\r\n    $table-&gt;unsignedBigInteger(<span class=\"hljs-string\">'likable_id'<\/span>);\r\n    $table-&gt;string(<span class=\"hljs-string\">'likable_type'<\/span>);\r\n    $table-&gt;timestamps();\r\n});\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-28\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Storing Likes<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">To add a &#8220;like&#8221; for a post:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-29\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$user = App\\Models\\User::find(<span class=\"hljs-number\">1<\/span>);\r\n$post = App\\Models\\Post::find(<span class=\"hljs-number\">1<\/span>);\r\n\r\n$user-&gt;likes()-&gt;attach($post-&gt;id, &#91;<span class=\"hljs-string\">'likable_type'<\/span> =&gt; get_class($post)]);\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-29\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Retrieving Likes<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">To retrieve all posts that a user has liked:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-30\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$likedPosts = $user-&gt;likes()-&gt;where(<span class=\"hljs-string\">'likable_type'<\/span>, App\\Models\\Post::class)-&gt;get();\r\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-30\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">You can do the same to get all the <code>Photos<\/code> or <code>Comments<\/code> that a user has liked.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By utilizing many-to-many polymorphic relationships, you can keep your database schema and Eloquent models clean and maintainable, all while achieving complex data relations.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Custom Polymorphic Types<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">How to Customize Polymorphic Type Columns<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">By default, Eloquent uses the fully qualified class name (FQCN) of the related model to store the type of the polymorphic relation. While this works well, there may be instances where you&#8217;d like to customize how Eloquent determines these types. For example, you might prefer a shorter, more readable version for database storage, or you might need to interact with a database where the types have already been defined differently.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Laravel provides a way to customize these types using the <code>Relation::morphMap<\/code> method. You can typically call this method in the <code>boot<\/code> method of your <code>AppServiceProvider<\/code>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example<\/h4>\n\n\n\n<h5 class=\"wp-block-heading\">Setting up the Morph Map<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">In the <code>boot<\/code> method of your <code>AppServiceProvider<\/code>, define your custom morph map.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-31\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">Illuminate<\/span>\\<span class=\"hljs-title\">Database<\/span>\\<span class=\"hljs-title\">Eloquent<\/span>\\<span class=\"hljs-title\">Relations<\/span>\\<span class=\"hljs-title\">Relation<\/span>;\r\n\r\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">boot<\/span><span class=\"hljs-params\">()<\/span>\r\n<\/span>{\r\n    Relation::morphMap(&#91;\r\n        <span class=\"hljs-string\">'post'<\/span> =&gt; \\App\\Models\\Post::class,\r\n        <span class=\"hljs-string\">'photo'<\/span> =&gt; \\App\\Models\\Photo::class,\r\n        <span class=\"hljs-string\">'comment'<\/span> =&gt; \\App\\Models\\Comment::class,\r\n    ]);\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-31\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In this example, instead of storing the full class names, Eloquent will store the custom string keys (<code>'post'<\/code>, <code>'photo'<\/code>, <code>'comment'<\/code>) in the <code>_type<\/code> column of the polymorphic tables.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">Using Custom Types in Models<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Now that you&#8217;ve set up a morph map, you&#8217;ll interact with your polymorphic relations just like you normally would. Eloquent will automatically use the custom types when writing or reading from the database.<\/p>\n\n\n\n<h6 class=\"wp-block-heading\">Storing with Custom Types<\/h6>\n\n\n\n<p class=\"wp-block-paragraph\">For example, if you were to save a &#8220;like&#8221; for a <code>Post<\/code> model, the <code>likable_type<\/code> would be saved as <code>'post'<\/code> instead of the complete namespace <code>\\App\\Models\\Post<\/code>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-32\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$user = App\\Models\\User::find(<span class=\"hljs-number\">1<\/span>);\r\n$post = App\\Models\\Post::find(<span class=\"hljs-number\">1<\/span>);\r\n\r\n$user-&gt;likes()-&gt;attach($post-&gt;id, &#91;<span class=\"hljs-string\">'likable_type'<\/span> =&gt; <span class=\"hljs-string\">'post'<\/span>]);\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-32\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h6 class=\"wp-block-heading\">Retrieving with Custom Types<\/h6>\n\n\n\n<p class=\"wp-block-paragraph\">Similarly, when you retrieve data, the custom type in the <code>likable_type<\/code> column will automatically be mapped back to the correct class name.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-33\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$likedPosts = $user-&gt;likes()-&gt;where(<span class=\"hljs-string\">'likable_type'<\/span>, <span class=\"hljs-string\">'post'<\/span>)-&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-33\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">By customizing the polymorphic types, you can make your database cleaner and potentially easier to read, while also gaining the flexibility to define how polymorphic associations are structured.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Dynamic Queries<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Dynamic Where Clauses<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Explanation and Use Case<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Dynamic query methods in Eloquent offer an elegant, expressive way to filter and manipulate data dynamically without necessarily having to write raw SQL queries. These methods can be particularly useful for building dynamic filters, complex search functionalities, or APIs that offer a variety of querying options.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The use case can vary, but suppose you are building an e-commerce platform, and you need to filter products based on multiple attributes like category, price range, brand, and so on. Dynamic query methods can simplify this operation significantly.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example<\/h4>\n\n\n\n<h5 class=\"wp-block-heading\">Basic Dynamic Where<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">In Laravel, you can dynamically call any <code>where<\/code> method by prefixing it with <code>where<\/code> and converting the snake_case name to StudlyCase.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, let&#8217;s say you have a <code>User<\/code> model with a <code>user_type<\/code> field. You can dynamically filter users based on this field as follows:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-34\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$users = \\App\\Models\\User::whereUserType(<span class=\"hljs-string\">'admin'<\/span>)-&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-34\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">This is equivalent to:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-35\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$users = \\App\\Models\\User::where(<span class=\"hljs-string\">'user_type'<\/span>, <span class=\"hljs-string\">'admin'<\/span>)-&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-35\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Chaining Dynamic Wheres<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">You can also chain multiple dynamic <code>where<\/code> clauses for more complex queries:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-36\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$users = \\App\\Models\\User::whereUserType(<span class=\"hljs-string\">'admin'<\/span>)\r\n                          -&gt;whereIsActive(<span class=\"hljs-keyword\">true<\/span>)\r\n                          -&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-36\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">This will generate SQL like:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-37\" data-shcb-language-name=\"SQL (Structured Query Language)\" data-shcb-language-slug=\"sql\"><span><code class=\"hljs language-sql\"><span class=\"hljs-keyword\">select<\/span> * <span class=\"hljs-keyword\">from<\/span> <span class=\"hljs-string\">`users`<\/span> <span class=\"hljs-keyword\">where<\/span> <span class=\"hljs-string\">`user_type`<\/span> = <span class=\"hljs-string\">'admin'<\/span> <span class=\"hljs-keyword\">and<\/span> <span class=\"hljs-string\">`is_active`<\/span> = <span class=\"hljs-number\">1<\/span>\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-37\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">SQL (Structured Query Language)<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">sql<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Using Dynamic Where with Relationships<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">You can apply dynamic where clauses even when you are eager-loading relationships:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-38\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$posts = \\App\\Models\\Post::with(&#91;<span class=\"hljs-string\">'comments'<\/span> =&gt; <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">($query)<\/span> <\/span>{\r\n    $query-&gt;whereIsApproved(<span class=\"hljs-keyword\">true<\/span>);\r\n}])-&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-38\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Here, the <code>whereIsApproved<\/code> dynamic where clause will only load the comments that are approved.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">Dynamic Where with Placeholders<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">You can also use placeholders in the method name and pass the values you want to compare as arguments:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-39\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$products = \\App\\Models\\Product::where(<span class=\"hljs-string\">'price'<\/span>, <span class=\"hljs-string\">'&gt;='<\/span>, <span class=\"hljs-number\">100<\/span>)\r\n                                -&gt;orWhereBetweenPrice(<span class=\"hljs-number\">200<\/span>, <span class=\"hljs-number\">500<\/span>)\r\n                                -&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-39\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">This allows you to take advantage of Eloquent&#8217;s query-building features while writing expressive, easy-to-understand code.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Query Macros<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Explanation and Use Case<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Query macros in Laravel allow you to extend the Eloquent query builder with custom methods, making it easier to reuse complex query logic throughout your application. This can be incredibly helpful when you have specific, complicated queries that you find yourself using often.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, let&#8217;s say you are building a blogging platform, and you often need to fetch the most commented posts. Instead of rewriting the same logic in multiple places, you could define a macro that handles this query and then call that macro whenever needed.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example<\/h4>\n\n\n\n<h5 class=\"wp-block-heading\">Defining a Query Macro<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">To define a macro, you can use the <code>macro<\/code> method on the <code>DB<\/code> facade&#8217;s <code>Query<\/code> class. Typically, this is done in a service provider, often within the <code>boot<\/code> method.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s how you could define a macro to fetch the most commented posts:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-40\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">Illuminate<\/span>\\<span class=\"hljs-title\">Database<\/span>\\<span class=\"hljs-title\">Query<\/span>\\<span class=\"hljs-title\">Builder<\/span>;\r\n\r\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">boot<\/span><span class=\"hljs-params\">()<\/span>\r\n<\/span>{\r\n    Builder::macro(<span class=\"hljs-string\">'mostCommented'<\/span>, <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">()<\/span> <\/span>{\r\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">$this<\/span>-&gt;orderBy(<span class=\"hljs-string\">'comments_count'<\/span>, <span class=\"hljs-string\">'desc'<\/span>);\r\n    });\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-40\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Now, the <code>mostCommented<\/code> macro can be used like any other Eloquent query builder method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-41\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$mostCommentedPosts = \\App\\Models\\Post::query()\r\n    -&gt;mostCommented()\r\n    -&gt;take(<span class=\"hljs-number\">5<\/span>)\r\n    -&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-41\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">This will fetch the top 5 most commented posts.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Query Macros with Parameters<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Macros can also accept parameters. For instance, you might want to specify how many &#8220;most commented&#8221; posts to retrieve dynamically:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-42\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">Builder::macro(<span class=\"hljs-string\">'mostCommented'<\/span>, <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">($limit = <span class=\"hljs-number\">5<\/span>)<\/span> <\/span>{\r\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">$this<\/span>-&gt;orderBy(<span class=\"hljs-string\">'comments_count'<\/span>, <span class=\"hljs-string\">'desc'<\/span>)-&gt;limit($limit);\r\n});\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-42\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">You can then call the macro with a parameter:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-43\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$mostCommentedPosts = \\App\\Models\\Post::query()\r\n    -&gt;mostCommented(<span class=\"hljs-number\">10<\/span>)\r\n    -&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-43\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">This will fetch the top 10 most commented posts.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Query Macros in Relationships<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">You can also use query macros when you&#8217;re eager-loading relationships:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-44\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$users = \\App\\Models\\User::with(&#91;<span class=\"hljs-string\">'posts'<\/span> =&gt; <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">($query)<\/span> <\/span>{\r\n    $query-&gt;mostCommented();\r\n}])-&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-44\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Here, for each user, only the most commented posts would be eager-loaded.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By using query macros, you can create a more maintainable and clean codebase, keeping your query logic centralized and reusable.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Custom Accessors and Mutators<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Defining an Accessor<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Explanation and Use Case<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Accessors and mutators allow you to format Eloquent attribute values when you retrieve them from a model or set them on a model. Accessors transform an attribute value when you access it, while mutators transform the value before saving it to the database.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Accessors can be useful in various scenarios where you want to manipulate or format the data after fetching it but before using it in your application. For example, you may want to concatenate the first name and last name fields to display the full name of a user.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example<\/h4>\n\n\n\n<h5 class=\"wp-block-heading\">The Model<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s an example in which we define an accessor within a <code>User<\/code> model to create a <code>full_name<\/code> attribute from <code>first_name<\/code> and <code>last_name<\/code>.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-45\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-keyword\">namespace<\/span> <span class=\"hljs-title\">App<\/span>\\<span class=\"hljs-title\">Models<\/span>;\r\n\r\n<span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">Illuminate<\/span>\\<span class=\"hljs-title\">Database<\/span>\\<span class=\"hljs-title\">Eloquent<\/span>\\<span class=\"hljs-title\">Model<\/span>;\r\n\r\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">User<\/span> <span class=\"hljs-keyword\">extends<\/span> <span class=\"hljs-title\">Model<\/span>\r\n<\/span>{\r\n    <span class=\"hljs-comment\">\/\/ Defining an accessor<\/span>\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">getFullNameAttribute<\/span><span class=\"hljs-params\">()<\/span>\r\n    <\/span>{\r\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-string\">\"{$this-&gt;first_name} {$this-&gt;last_name}\"<\/span>;\r\n    }\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-45\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Usage in a Controller<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Now, whenever you retrieve a <code>User<\/code> model, you can access this computed <code>full_name<\/code> field as if it was a regular column on the database.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-46\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$user = User::find(<span class=\"hljs-number\">1<\/span>);\n$fullName = $user-&gt;full_name;  <span class=\"hljs-comment\">\/\/ This will automatically use the getFullNameAttribute accessor<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-46\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">JSON Representation<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">The accessor will also apply when you convert a model to an array or JSON:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-47\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-keyword\">return<\/span> response()-&gt;json($user);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-47\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">This will include a <code>full_name<\/code> field in the JSON representation of the user, assuming <code>first_name<\/code> and <code>last_name<\/code> exist and are populated.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By using custom accessors, you can ensure that the data you work with is always in the format you expect, without having to repeatedly apply the same transformations.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Defining a Mutator<\/h1>\n\n\n\n<h2 class=\"wp-block-heading\">Explanation and Use Case<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">While accessors modify attributes when you access them on a model, mutators are used to alter attributes before saving them to the database. Mutators are particularly useful for consistently transforming data before it&#8217;s stored. For instance, you might want to ensure that all email addresses are stored in lowercase, or you may wish to hash passwords before saving them.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Code Example<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">The Model<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To define a mutator, you&#8217;ll define a method on your Eloquent model. The method should be named <code>set{AttributeName}Attribute<\/code>, where <code>{AttributeName}<\/code> is the StudlyCase version of your column name.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is an example within a <code>User<\/code> model to hash a password before storing it:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-48\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-keyword\">namespace<\/span> <span class=\"hljs-title\">App<\/span>\\<span class=\"hljs-title\">Models<\/span>;\r\n\r\n<span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">Illuminate<\/span>\\<span class=\"hljs-title\">Database<\/span>\\<span class=\"hljs-title\">Eloquent<\/span>\\<span class=\"hljs-title\">Model<\/span>;\r\n<span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">Illuminate<\/span>\\<span class=\"hljs-title\">Support<\/span>\\<span class=\"hljs-title\">Facades<\/span>\\<span class=\"hljs-title\">Hash<\/span>;\r\n\r\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">User<\/span> <span class=\"hljs-keyword\">extends<\/span> <span class=\"hljs-title\">Model<\/span>\r\n<\/span>{\r\n    <span class=\"hljs-comment\">\/\/ Defining a mutator<\/span>\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">setPasswordAttribute<\/span><span class=\"hljs-params\">($value)<\/span>\r\n    <\/span>{\r\n        <span class=\"hljs-keyword\">$this<\/span>-&gt;attributes&#91;<span class=\"hljs-string\">'password'<\/span>] = Hash::make($value);\r\n    }\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-48\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\">Usage in a Controller<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Now, when you set the <code>password<\/code> attribute on a <code>User<\/code> model, the mutator will automatically hash the password before it gets saved to the database.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-49\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$user = <span class=\"hljs-keyword\">new<\/span> User;\r\n$user-&gt;password = <span class=\"hljs-string\">'plain-text-password'<\/span>;  <span class=\"hljs-comment\">\/\/ The mutator will automatically hash this password<\/span>\r\n$user-&gt;save();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-49\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Or when updating a password:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-50\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$user = User::find(<span class=\"hljs-number\">1<\/span>);\r\n$user-&gt;password = <span class=\"hljs-string\">'new-plain-text-password'<\/span>;  <span class=\"hljs-comment\">\/\/ The mutator hashes the new password<\/span>\r\n$user-&gt;save();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-50\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\">Bulk Updates<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Note that mutators will not run during bulk updates made through query builder methods like <code>update()<\/code>. They only work when you&#8217;re saving individual model instances.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-51\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">\/\/ This will NOT use the setPasswordAttribute mutator<\/span>\r\nUser::where(<span class=\"hljs-string\">'condition'<\/span>, $condition)-&gt;update(&#91;<span class=\"hljs-string\">'password'<\/span> =&gt; <span class=\"hljs-string\">'new-plain-text-password'<\/span>]);\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-51\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">By defining custom mutators, you can easily enforce data integrity and consistency when saving models, without having to manually apply the same transformations each time.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Pivot Tables and Many-to-Many Relationships<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Basic Many-to-Many<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Explanation and Use Case<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Many-to-many relationships are a fundamental concept in relational databases and are implemented using &#8220;pivot&#8221; tables. In the context of an application, you might have entities that require a many-to-many relationship with each other. For example, in a blogging platform, a post could have multiple tags, and a tag can be associated with multiple posts.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Laravel&#8217;s Eloquent ORM provides a straightforward and readable API to interact with these types of relationships. By learning how to leverage Eloquent to manipulate many-to-many relationships, you can make your codebase cleaner and more maintainable.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example<\/h4>\n\n\n\n<h5 class=\"wp-block-heading\">Database Migrations<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">First, let&#8217;s consider that we have two tables: <code>posts<\/code> and <code>tags<\/code>. We&#8217;ll use a pivot table to link them, typically named using the singular names of the two tables, sorted alphabetically: <code>post_tag<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is what the migrations might look like:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-52\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">\/\/ posts table migration<\/span>\r\nSchema::create(<span class=\"hljs-string\">'posts'<\/span>, <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">(Blueprint $table)<\/span> <\/span>{\r\n    $table-&gt;id();\r\n    $table-&gt;string(<span class=\"hljs-string\">'title'<\/span>);\r\n    $table-&gt;text(<span class=\"hljs-string\">'content'<\/span>);\r\n    $table-&gt;timestamps();\r\n});\r\n\r\n<span class=\"hljs-comment\">\/\/ tags table migration<\/span>\r\nSchema::create(<span class=\"hljs-string\">'tags'<\/span>, <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">(Blueprint $table)<\/span> <\/span>{\r\n    $table-&gt;id();\r\n    $table-&gt;string(<span class=\"hljs-string\">'name'<\/span>);\r\n    $table-&gt;timestamps();\r\n});\r\n\r\n<span class=\"hljs-comment\">\/\/ post_tag pivot table migration<\/span>\r\nSchema::create(<span class=\"hljs-string\">'post_tag'<\/span>, <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">(Blueprint $table)<\/span> <\/span>{\r\n    $table-&gt;id();\r\n    $table-&gt;foreignId(<span class=\"hljs-string\">'post_id'<\/span>)-&gt;constrained()-&gt;onDelete(<span class=\"hljs-string\">'cascade'<\/span>);\r\n    $table-&gt;foreignId(<span class=\"hljs-string\">'tag_id'<\/span>)-&gt;constrained()-&gt;onDelete(<span class=\"hljs-string\">'cascade'<\/span>);\r\n});\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-52\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">The Eloquent Models<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">In the <code>Post<\/code> and <code>Tag<\/code> models, you can define the many-to-many relationship like so:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-53\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">\/\/ Post.php<\/span>\r\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">tags<\/span><span class=\"hljs-params\">()<\/span>\r\n<\/span>{\r\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">$this<\/span>-&gt;belongsToMany(Tag::class);\r\n}\r\n\r\n<span class=\"hljs-comment\">\/\/ Tag.php<\/span>\r\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">posts<\/span><span class=\"hljs-params\">()<\/span>\r\n<\/span>{\r\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">$this<\/span>-&gt;belongsToMany(Post::class);\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-53\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Attaching Tags to a Post<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">To associate tags with a post, you can use the <code>attach<\/code> method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-54\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$post = \\App\\Models\\Post::find(<span class=\"hljs-number\">1<\/span>);\r\n$tag1 = \\App\\Models\\Tag::find(<span class=\"hljs-number\">1<\/span>);\r\n$tag2 = \\App\\Models\\Tag::find(<span class=\"hljs-number\">2<\/span>);\r\n\r\n<span class=\"hljs-comment\">\/\/ Attaching single tag<\/span>\r\n$post-&gt;tags()-&gt;attach($tag1);\r\n\r\n<span class=\"hljs-comment\">\/\/ Attaching multiple tags<\/span>\r\n$post-&gt;tags()-&gt;attach(&#91;$tag1-&gt;id, $tag2-&gt;id]);\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-54\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Retrieving Related Tags<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">To get the tags associated with a post:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-55\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$tags = $post-&gt;tags;\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-55\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Detaching Tags<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">To remove the relationship, you can use the <code>detach<\/code> method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-56\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">\/\/ Detach a specific tag<\/span>\r\n$post-&gt;tags()-&gt;detach($tag1);\r\n\r\n<span class=\"hljs-comment\">\/\/ Detach all tags from a post<\/span>\r\n$post-&gt;tags()-&gt;detach();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-56\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\">Customizing Pivot Table Data<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Explanation and Use Case<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Pivot tables not only serve to establish the links between the related models in a many-to-many relationship but also can store additional data relevant to the relationship itself. For instance, in a social media application, a pivot table that connects <code>users<\/code> and <code>roles<\/code> tables might also have a <code>created_at<\/code> column indicating when a user was assigned a particular role.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Using Eloquent&#8217;s advanced features, you can effortlessly interact with this additional pivot table data.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example<\/h4>\n\n\n\n<h5 class=\"wp-block-heading\">Database Migration<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s extend our existing <code>post_tag<\/code> pivot table to include an <code>is_featured<\/code> column, which will indicate whether a tag is featured for a particular post.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-57\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">\/\/ Update the post_tag table migration<\/span>\r\nSchema::table(<span class=\"hljs-string\">'post_tag'<\/span>, <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">(Blueprint $table)<\/span> <\/span>{\r\n    $table-&gt;boolean(<span class=\"hljs-string\">'is_featured'<\/span>)-&gt;default(<span class=\"hljs-keyword\">false<\/span>);\r\n});\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-57\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\">Model Configuration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Next, update your Eloquent models to make Eloquent aware of the new pivot table field. Use the <code>withPivot<\/code> method to specify additional fields on the pivot table.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-58\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">\/\/ Post.php<\/span>\r\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">tags<\/span><span class=\"hljs-params\">()<\/span>\r\n<\/span>{\r\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">$this<\/span>-&gt;belongsToMany(Tag::class)-&gt;withPivot(<span class=\"hljs-string\">'is_featured'<\/span>);\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-58\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\">Storing Data in the Pivot Table<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">You can add data to the pivot table while attaching models:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-59\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$post = \\App\\Models\\Post::find(<span class=\"hljs-number\">1<\/span>);\r\n$tag = \\App\\Models\\Tag::find(<span class=\"hljs-number\">1<\/span>);\r\n\r\n<span class=\"hljs-comment\">\/\/ Attach a tag and mark it as featured<\/span>\r\n$post-&gt;tags()-&gt;attach($tag, &#91;<span class=\"hljs-string\">'is_featured'<\/span> =&gt; <span class=\"hljs-keyword\">true<\/span>]);\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-59\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\">Accessing Data in the Pivot Table<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To access these additional fields when you retrieve the relationship, you can access the <code>pivot<\/code> attribute on the model instance:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-60\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$tags = $post-&gt;tags;\r\n\r\n<span class=\"hljs-keyword\">foreach<\/span> ($tags <span class=\"hljs-keyword\">as<\/span> $tag) {\r\n    <span class=\"hljs-keyword\">echo<\/span> $tag-&gt;pivot-&gt;is_featured; <span class=\"hljs-comment\">\/\/ Output: 1 or 0<\/span>\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-60\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\">Updating Data in the Pivot Table<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">You can update these additional fields using the <code>sync<\/code> or <code>updateExistingPivot<\/code> methods:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-61\" data-shcb-language-name=\"Mojolicious\" data-shcb-language-slug=\"mojolicious\"><span><code class=\"hljs language-mojolicious\"><span class=\"xml\">\/\/ Using updateExistingPivot\r\n$post-&gt;tags()-&gt;updateExistingPivot($tag, &#91;'is_featured' =&gt; false]);\r\n\r\n\/\/ Using sync with pivot attributes\r\n$post-&gt;tags()-&gt;sync(&#91;\r\n    $tag-&gt;id =&gt; &#91;'is_featured' =&gt; true]\r\n]);\r<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-61\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Mojolicious<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">mojolicious<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h3 class=\"wp-block-heading\">Filtering via Pivot Table<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Explanation and Use Case<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Once you have additional data in your pivot tables, there may be scenarios where you&#8217;d want to filter your results based on these pivot table attributes. For example, in a content management system, you might want to retrieve all posts tagged with a &#8220;featured&#8221; tag.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Laravel&#8217;s Eloquent makes this fairly simple and expressive. You can use the <code>wherePivot<\/code> and related methods to filter your many-to-many relationship queries.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example<\/h4>\n\n\n\n<h5 class=\"wp-block-heading\">Model Configuration<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Make sure you have the <code>withPivot<\/code> method specified to indicate the additional fields:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-62\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">\/\/ Post.php<\/span>\r\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">tags<\/span><span class=\"hljs-params\">()<\/span>\r\n<\/span>{\r\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">$this<\/span>-&gt;belongsToMany(Tag::class)-&gt;withPivot(<span class=\"hljs-string\">'is_featured'<\/span>);\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-62\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Filtering Posts with Featured Tags<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">To get all posts where the <code>is_featured<\/code> attribute in the pivot table is <code>true<\/code>, you can do the following:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-63\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$featuredPosts = \\App\\Models\\Post::whereHas(<span class=\"hljs-string\">'tags'<\/span>, <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">($query)<\/span> <\/span>{\r\n    $query-&gt;where(<span class=\"hljs-string\">'is_featured'<\/span>, <span class=\"hljs-keyword\">true<\/span>);\r\n})-&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-63\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Retrieving Tags and Filtering via Pivot<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">To retrieve all tags that are marked as &#8220;featured&#8221; for a specific post:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-64\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$featuredTags = $post-&gt;tags()-&gt;wherePivot(<span class=\"hljs-string\">'is_featured'<\/span>, <span class=\"hljs-keyword\">true<\/span>)-&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-64\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Multiple Conditions<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">If you have multiple conditions, you can chain them:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-65\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$filteredPosts = \\App\\Models\\Post::whereHas(<span class=\"hljs-string\">'tags'<\/span>, <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">($query)<\/span> <\/span>{\r\n    $query-&gt;where(<span class=\"hljs-string\">'is_featured'<\/span>, <span class=\"hljs-keyword\">true<\/span>)\r\n          -&gt;where(<span class=\"hljs-string\">'name'<\/span>, <span class=\"hljs-string\">'Laravel'<\/span>);\r\n})-&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-65\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Using the <code>orWherePivot<\/code> Method<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">If you want to apply an &#8220;OR&#8221; condition on the pivot table fields, you can use the <code>orWherePivot<\/code> method:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-66\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$tags = $post-&gt;tags()\r\n             -&gt;wherePivot(<span class=\"hljs-string\">'is_featured'<\/span>, <span class=\"hljs-keyword\">true<\/span>)\r\n             -&gt;orWherePivot(<span class=\"hljs-string\">'other_field'<\/span>, <span class=\"hljs-string\">'value'<\/span>)\r\n             -&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-66\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">By understanding how to filter via pivot tables, you have even more power to represent and query complex relationships in your applications efficiently.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Optimizing Eloquent for Performance<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Using <code>select()<\/code> Wisely<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Explanation and Use Case<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">When dealing with large-scale applications, performance can become a concern. Eloquent makes interacting with your database exceptionally easy but can sometimes lead to suboptimal queries if not used carefully. One way to improve performance is to restrict the columns returned from your queries by using the <code>select()<\/code> method. This is particularly useful when you don&#8217;t need every column in the table, thereby reducing the amount of data transferred between your application and the database.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example<\/h4>\n\n\n\n<h5 class=\"wp-block-heading\">Retrieving All Columns (Not Recommended)<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s how you might retrieve all columns for all rows of a table:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-67\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$posts = \\App\\Models\\Post::all();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-67\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">This could be resource-intensive if your <code>posts<\/code> table has many columns and rows.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">Using <code>select()<\/code> to Limit Columns<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">You can use <code>select()<\/code> to specify exactly which columns you want:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-68\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$posts = \\App\\Models\\Post::select(<span class=\"hljs-string\">'id'<\/span>, <span class=\"hljs-string\">'title'<\/span>)-&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-68\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Nested Relationships<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">You can also use <code>select()<\/code> when you&#8217;re eager-loading relationships to limit the columns retrieved from related tables.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-69\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$posts = \\App\\Models\\Post::with(&#91;<span class=\"hljs-string\">'tags'<\/span> =&gt; <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">($query)<\/span> <\/span>{\r\n    $query-&gt;select(<span class=\"hljs-string\">'id'<\/span>, <span class=\"hljs-string\">'name'<\/span>);\r\n}])-&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-69\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Combining <code>select()<\/code> with Other Eloquent Methods<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">You can chain <code>select()<\/code> with other Eloquent methods to further optimize your query:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-70\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$featuredPosts = \\App\\Models\\Post::whereHas(<span class=\"hljs-string\">'tags'<\/span>, <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">($query)<\/span> <\/span>{\r\n    $query-&gt;where(<span class=\"hljs-string\">'is_featured'<\/span>, <span class=\"hljs-keyword\">true<\/span>);\r\n})-&gt;select(<span class=\"hljs-string\">'id'<\/span>, <span class=\"hljs-string\">'title'<\/span>)-&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-70\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">By using <code>select()<\/code> wisely, you can significantly improve the performance of your Eloquent queries, especially in scenarios where you&#8217;re dealing with large datasets.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Caching Eloquent Queries<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Explanation and Use Case<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Database operations are often one of the most resource-intensive parts of an application. In a read-heavy application, executing the same queries repeatedly can be a significant bottleneck. Eloquent provides built-in support for query caching, which can drastically reduce the number of queries that need to be executed against a database, improving performance and reducing latency.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Query caching is especially useful in scenarios where the data doesn&#8217;t change frequently but is read often. For instance, a list of categories on an e-commerce site that rarely changes could be a perfect candidate for caching.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example<\/h4>\n\n\n\n<h5 class=\"wp-block-heading\">Simple Caching<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">You can cache an Eloquent query&#8217;s results using Laravel&#8217;s caching system like so:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-71\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">Illuminate<\/span>\\<span class=\"hljs-title\">Support<\/span>\\<span class=\"hljs-title\">Facades<\/span>\\<span class=\"hljs-title\">Cache<\/span>;\r\n\r\n$posts = Cache::remember(<span class=\"hljs-string\">'all-posts'<\/span>, <span class=\"hljs-number\">60<\/span>, <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">()<\/span> <\/span>{\r\n    <span class=\"hljs-keyword\">return<\/span> \\App\\Models\\Post::all();\r\n});\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-71\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Here, the query to retrieve all posts is cached for 60 minutes. If another request queries for all posts within the next 60 minutes, the cached version will be returned instead of hitting the database.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">Conditional Caching<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">If you want to cache queries conditionally, you can use <code>Cache::remember<\/code> along with additional checks:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-72\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$posts = Cache::remember(<span class=\"hljs-string\">'featured-posts'<\/span>, <span class=\"hljs-number\">60<\/span>, <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">()<\/span> <\/span>{\r\n    <span class=\"hljs-keyword\">return<\/span> \\App\\Models\\Post::whereHas(<span class=\"hljs-string\">'tags'<\/span>, <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">($query)<\/span> <\/span>{\r\n        $query-&gt;where(<span class=\"hljs-string\">'is_featured'<\/span>, <span class=\"hljs-keyword\">true<\/span>);\r\n    })-&gt;get();\r\n});\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-72\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Cache Tags for Complex Invalidation<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">In more complex scenarios where you need to invalidate multiple related cache entries, you can use cache tags:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-73\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">Cache::tags(&#91;<span class=\"hljs-string\">'posts'<\/span>])-&gt;put(<span class=\"hljs-string\">'all-posts'<\/span>, $posts, <span class=\"hljs-number\">60<\/span>);\r\nCache::tags(&#91;<span class=\"hljs-string\">'posts'<\/span>, <span class=\"hljs-string\">'tags'<\/span>])-&gt;put(<span class=\"hljs-string\">'featured-posts'<\/span>, $featuredPosts, <span class=\"hljs-number\">60<\/span>);\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-73\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">To invalidate all cache entries with a specific tag:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-74\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">Cache::tags(<span class=\"hljs-string\">'posts'<\/span>)-&gt;flush();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-74\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Automatic Cache Invalidation<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">For even more control, you can use Eloquent model events to clear the cache automatically when the data changes:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-75\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">\/\/ AppServiceProvider.php<\/span>\r\n\r\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">boot<\/span><span class=\"hljs-params\">()<\/span>\r\n<\/span>{\r\n    \\App\\Models\\Post::updated(<span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">($post)<\/span> <\/span>{\r\n        Cache::tags(<span class=\"hljs-string\">'posts'<\/span>)-&gt;flush();\r\n    });\r\n\r\n    \\App\\Models\\Post::deleted(<span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">($post)<\/span> <\/span>{\r\n        Cache::tags(<span class=\"hljs-string\">'posts'<\/span>)-&gt;flush();\r\n    });\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-75\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">This ensures that the cache remains consistent with the database.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Caching can be a very effective tool for improving your Laravel application&#8217;s performance. By understanding how to cache Eloquent queries, you can take a significant load off your database, thereby making your applications faster and more efficient.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Query Debugging Techniques<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Using <code>toSql()<\/code><\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Explanation and Use Case<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">As your application grows, debugging database queries can become increasingly complex. Eloquent&#8217;s fluent interface abstracts a lot of the database queries for you. However, there are times when you may need to see the raw SQL to debug performance issues or verify the query being executed. This is where the <code>toSql()<\/code> method comes in handy.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>toSql()<\/code> method allows you to see the SQL query that would be executed, without actually executing it. This is particularly useful when you&#8217;re trying to debug complex queries involving multiple joins, sub-queries, or intricate where conditions.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example<\/h4>\n\n\n\n<h5 class=\"wp-block-heading\">Basic Usage<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s a simple way to use <code>toSql()<\/code> to preview the SQL query for a basic Eloquent query:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-76\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$query = \\App\\Models\\Post::where(<span class=\"hljs-string\">'published'<\/span>, <span class=\"hljs-keyword\">true<\/span>)-&gt;toSql();\r\n\r\n<span class=\"hljs-comment\">\/\/ Outputs: \"select * from `posts` where `published` = ?\"<\/span>\r\n<span class=\"hljs-keyword\">echo<\/span> $query;\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-76\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">With Bindings<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Note that <code>toSql()<\/code> doesn&#8217;t show the actual values for the bindings. To get the fully compiled SQL query, you can combine <code>toSql()<\/code> with <code>getBindings()<\/code>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-77\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$query = \\App\\Models\\Post::where(<span class=\"hljs-string\">'published'<\/span>, <span class=\"hljs-keyword\">true<\/span>);\r\n$sql = str_replace(<span class=\"hljs-string\">'?'<\/span>, <span class=\"hljs-string\">\"'{$query-&gt;getBindings()&#91;0]}'\"<\/span>, $query-&gt;toSql());\r\n\r\n<span class=\"hljs-comment\">\/\/ Outputs: \"select * from `posts` where `published` = '1'\"<\/span>\r\n<span class=\"hljs-keyword\">echo<\/span> $sql;\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-77\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Complex Queries<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">For more complex queries involving relationships, you can also use <code>toSql()<\/code>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-78\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$query = \\App\\Models\\Post::whereHas(<span class=\"hljs-string\">'tags'<\/span>, <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">($query)<\/span> <\/span>{\r\n    $query-&gt;where(<span class=\"hljs-string\">'name'<\/span>, <span class=\"hljs-string\">'laravel'<\/span>);\r\n})-&gt;toSql();\r\n\r\n<span class=\"hljs-comment\">\/\/ Outputs: \"select * from `posts` where exists (select * from `tags` inner join `post_tag` on ... where `posts`.`id` = `post_tag`.`post_id` and `name` = ?)\"<\/span>\r\n<span class=\"hljs-keyword\">echo<\/span> $query;\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-78\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">By using <code>toSql()<\/code>, you can peek into what Eloquent is doing behind the scenes. This is immensely useful for debugging and can also serve as an educational tool to understand how Eloquent translates fluent method chaining into raw SQL queries.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Database Query Log<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Explanation and Use Case<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Even with tools like <code>toSql()<\/code>, sometimes you may need more insights into all the queries that are executed during a request cycle. For example, you might be facing performance issues due to redundant queries or &#8220;N+1 query problems.&#8221; Laravel offers a feature known as the Query Log to help you tackle these issues.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The Query Log keeps a record of all queries executed during a request. This can be incredibly helpful for debugging, profiling, and optimizing your application&#8217;s database interactions.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example<\/h4>\n\n\n\n<h5 class=\"wp-block-heading\">Enabling the Query Log<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Before you can view the queries, you must first enable the Query Log:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-79\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">Illuminate<\/span>\\<span class=\"hljs-title\">Support<\/span>\\<span class=\"hljs-title\">Facades<\/span>\\<span class=\"hljs-title\">DB<\/span>;\r\n\r\nDB::enableQueryLog();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-79\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Run Some Queries<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Now, let&#8217;s run some queries to populate the Query Log.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-80\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$posts = \\App\\Models\\Post::where(<span class=\"hljs-string\">'published'<\/span>, <span class=\"hljs-keyword\">true<\/span>)-&gt;get();\r\n$users = \\App\\Models\\User::where(<span class=\"hljs-string\">'active'<\/span>, <span class=\"hljs-keyword\">true<\/span>)-&gt;get();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-80\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Retrieving and Viewing the Query Log<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">After running some queries, you can retrieve and view them like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-81\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">$queryLog = DB::getQueryLog();\r\n\r\nprint_r($queryLog);\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-81\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The output will be an array containing information about each executed query, such as the SQL query, bindings, and execution time.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">Example Output<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">The output might look something like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-82\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-keyword\">Array<\/span>\r\n(\r\n    &#91;<span class=\"hljs-number\">0<\/span>] =&gt; <span class=\"hljs-keyword\">Array<\/span>\r\n        (\r\n            &#91;query] =&gt; <span class=\"hljs-string\">\"select * from `posts` where `published` = ?\"<\/span>\r\n            &#91;bindings] =&gt; <span class=\"hljs-keyword\">Array<\/span>\r\n                (\r\n                    &#91;<span class=\"hljs-number\">0<\/span>] =&gt; <span class=\"hljs-number\">1<\/span>\r\n                )\r\n            &#91;time] =&gt; <span class=\"hljs-number\">0.32<\/span>\r\n        )\r\n    &#91;<span class=\"hljs-number\">1<\/span>] =&gt; <span class=\"hljs-keyword\">Array<\/span>\r\n        (\r\n            &#91;query] =&gt; <span class=\"hljs-string\">\"select * from `users` where `active` = ?\"<\/span>\r\n            &#91;bindings] =&gt; <span class=\"hljs-keyword\">Array<\/span>\r\n                (\r\n                    &#91;<span class=\"hljs-number\">0<\/span>] =&gt; <span class=\"hljs-number\">1<\/span>\r\n                )\r\n            &#91;time] =&gt; <span class=\"hljs-number\">0.22<\/span>\r\n        )\r\n)\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-82\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Disabling the Query Log<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">After you&#8217;re done debugging, it&#8217;s a good idea to disable the Query Log to free up memory:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-83\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">DB::disableQueryLog();\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-83\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">By using the Query Log feature, you can gain a comprehensive overview of all queries run during a request, making it easier to spot inefficiencies and improve performance.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Testing Eloquent Models<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Factory States<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Explanation and Use Case<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Testing is an essential part of any mature software development process, and when it comes to Laravel, Eloquent models are often at the heart of your application logic. Ensuring they behave as expected is crucial. Factory states in Laravel provide a powerful way to create different variations of a model while reusing common attributes, which can significantly streamline your testing process.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Factory states are especially useful in situations where you have a base model that can be in various states. For example, a <code>Post<\/code> model could have states like &#8216;draft&#8217;, &#8216;published&#8217;, or &#8216;archived&#8217;.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example<\/h4>\n\n\n\n<h5 class=\"wp-block-heading\">Define Factory States<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">First, let&#8217;s define some states for a <code>Post<\/code> model in its corresponding factory:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-84\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">Illuminate<\/span>\\<span class=\"hljs-title\">Database<\/span>\\<span class=\"hljs-title\">Eloquent<\/span>\\<span class=\"hljs-title\">Factories<\/span>\\<span class=\"hljs-title\">Factory<\/span>;\r\n\r\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">PostFactory<\/span> <span class=\"hljs-keyword\">extends<\/span> <span class=\"hljs-title\">Factory<\/span>\r\n<\/span>{\r\n    <span class=\"hljs-keyword\">protected<\/span> $model = \\App\\Models\\Post::class;\r\n\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">definition<\/span><span class=\"hljs-params\">()<\/span>\r\n    <\/span>{\r\n        <span class=\"hljs-keyword\">return<\/span> &#91;\r\n            <span class=\"hljs-string\">'title'<\/span> =&gt; <span class=\"hljs-keyword\">$this<\/span>-&gt;faker-&gt;sentence,\r\n            <span class=\"hljs-string\">'content'<\/span> =&gt; <span class=\"hljs-keyword\">$this<\/span>-&gt;faker-&gt;text,\r\n            <span class=\"hljs-string\">'published'<\/span> =&gt; <span class=\"hljs-keyword\">false<\/span>,\r\n        ];\r\n    }\r\n\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">published<\/span><span class=\"hljs-params\">()<\/span>\r\n    <\/span>{\r\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">$this<\/span>-&gt;state(&#91;\r\n            <span class=\"hljs-string\">'published'<\/span> =&gt; <span class=\"hljs-keyword\">true<\/span>,\r\n        ]);\r\n    }\r\n\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">draft<\/span><span class=\"hljs-params\">()<\/span>\r\n    <\/span>{\r\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">$this<\/span>-&gt;state(&#91;\r\n            <span class=\"hljs-string\">'published'<\/span> =&gt; <span class=\"hljs-keyword\">false<\/span>,\r\n        ]);\r\n    }\r\n\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">archived<\/span><span class=\"hljs-params\">()<\/span>\r\n    <\/span>{\r\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">$this<\/span>-&gt;state(&#91;\r\n            <span class=\"hljs-string\">'archived'<\/span> =&gt; <span class=\"hljs-keyword\">true<\/span>,\r\n        ]);\r\n    }\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-84\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Using Factory States in Tests<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Now you can use these states within your tests to create <code>Post<\/code> models in various states:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-85\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">App<\/span>\\<span class=\"hljs-title\">Models<\/span>\\<span class=\"hljs-title\">Post<\/span>;\r\n<span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">Illuminate<\/span>\\<span class=\"hljs-title\">Foundation<\/span>\\<span class=\"hljs-title\">Testing<\/span>\\<span class=\"hljs-title\">RefreshDatabase<\/span>;\r\n\r\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">PostTest<\/span> <span class=\"hljs-keyword\">extends<\/span> <span class=\"hljs-title\">TestCase<\/span>\r\n<\/span>{\r\n    <span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">RefreshDatabase<\/span>;\r\n\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">testPublishedPost<\/span><span class=\"hljs-params\">()<\/span>\r\n    <\/span>{\r\n        $post = Post::factory()-&gt;published()-&gt;create();\r\n\r\n        <span class=\"hljs-keyword\">$this<\/span>-&gt;assertTrue($post-&gt;published);\r\n    }\r\n\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">testDraftPost<\/span><span class=\"hljs-params\">()<\/span>\r\n    <\/span>{\r\n        $post = Post::factory()-&gt;draft()-&gt;create();\r\n\r\n        <span class=\"hljs-keyword\">$this<\/span>-&gt;assertFalse($post-&gt;published);\r\n    }\r\n\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">testArchivedPost<\/span><span class=\"hljs-params\">()<\/span>\r\n    <\/span>{\r\n        $post = Post::factory()-&gt;archived()-&gt;create();\r\n\r\n        <span class=\"hljs-keyword\">$this<\/span>-&gt;assertTrue($post-&gt;archived);\r\n    }\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-85\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">Factory states provide an elegant way to manage different versions of an Eloquent model during testing, making your test suite easier to work with and your tests easier to read and understand.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Eloquent Relationships in Testing<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Explanation and Use Case<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">In real-world applications, Eloquent models often interact with one another through relationships like one-to-one, one-to-many, many-to-many, and so forth. Testing these relationships is crucial to verify that your application&#8217;s different data models interact as expected.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For instance, consider a simple blogging platform where posts belong to users. You may want to verify that when a post is created, it&#8217;s correctly linked to a user. Or, you might want to ensure that when a user is deleted, all their posts are either deleted or disassociated, depending on the business requirements.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Code Example<\/h4>\n\n\n\n<h5 class=\"wp-block-heading\">Defining the Relationship<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Firstly, let&#8217;s assume you have a <code>User<\/code> model and a <code>Post<\/code> model with the following relationship:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-86\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">\/\/ In User.php<\/span>\r\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">posts<\/span><span class=\"hljs-params\">()<\/span>\r\n<\/span>{\r\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">$this<\/span>-&gt;hasMany(\\App\\Models\\Post::class);\r\n}\r\n\r\n<span class=\"hljs-comment\">\/\/ In Post.php<\/span>\r\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">user<\/span><span class=\"hljs-params\">()<\/span>\r\n<\/span>{\r\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">$this<\/span>-&gt;belongsTo(\\App\\Models\\User::class);\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-86\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Setting Up Factories<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">You&#8217;ll also want factories for both models. The <code>Post<\/code> factory will use a user ID to set up its foreign key:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-87\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\">\/\/ PostFactory.php<\/span>\r\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">definition<\/span><span class=\"hljs-params\">()<\/span>\r\n<\/span>{\r\n    <span class=\"hljs-keyword\">return<\/span> &#91;\r\n        <span class=\"hljs-string\">'title'<\/span> =&gt; <span class=\"hljs-keyword\">$this<\/span>-&gt;faker-&gt;sentence,\r\n        <span class=\"hljs-string\">'content'<\/span> =&gt; <span class=\"hljs-keyword\">$this<\/span>-&gt;faker-&gt;paragraph,\r\n        <span class=\"hljs-string\">'user_id'<\/span> =&gt; \\App\\Models\\User::factory(),\r\n    ];\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-87\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h5 class=\"wp-block-heading\">Writing the Tests<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Now, you can write tests to ensure that these relationships are functioning correctly:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-88\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">App<\/span>\\<span class=\"hljs-title\">Models<\/span>\\<span class=\"hljs-title\">Post<\/span>;\r\n<span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">App<\/span>\\<span class=\"hljs-title\">Models<\/span>\\<span class=\"hljs-title\">User<\/span>;\r\n<span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">Illuminate<\/span>\\<span class=\"hljs-title\">Foundation<\/span>\\<span class=\"hljs-title\">Testing<\/span>\\<span class=\"hljs-title\">RefreshDatabase<\/span>;\r\n\r\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">PostUserRelationshipTest<\/span> <span class=\"hljs-keyword\">extends<\/span> <span class=\"hljs-title\">TestCase<\/span>\r\n<\/span>{\r\n    <span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">RefreshDatabase<\/span>;\r\n\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">testPostBelongsToUser<\/span><span class=\"hljs-params\">()<\/span>\r\n    <\/span>{\r\n        $post = Post::factory()-&gt;create();\r\n        <span class=\"hljs-keyword\">$this<\/span>-&gt;assertInstanceOf(User::class, $post-&gt;user);\r\n    }\r\n\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">testUserHasManyPosts<\/span><span class=\"hljs-params\">()<\/span>\r\n    <\/span>{\r\n        $user = User::factory()-&gt;create();\r\n        Post::factory()-&gt;count(<span class=\"hljs-number\">3<\/span>)-&gt;create(&#91;<span class=\"hljs-string\">'user_id'<\/span> =&gt; $user-&gt;id]);\r\n\r\n        <span class=\"hljs-keyword\">$this<\/span>-&gt;assertEquals(<span class=\"hljs-number\">3<\/span>, $user-&gt;posts-&gt;count());\r\n    }\r\n\r\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">testDeletingUserDeletesPosts<\/span><span class=\"hljs-params\">()<\/span>\r\n    <\/span>{\r\n        $user = User::factory()-&gt;create();\r\n        Post::factory()-&gt;count(<span class=\"hljs-number\">3<\/span>)-&gt;create(&#91;<span class=\"hljs-string\">'user_id'<\/span> =&gt; $user-&gt;id]);\r\n\r\n        $user-&gt;delete();\r\n\r\n        <span class=\"hljs-keyword\">$this<\/span>-&gt;assertEquals(<span class=\"hljs-number\">0<\/span>, Post::count());\r\n    }\r\n}\r<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-88\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">In the above test cases:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>testPostBelongsToUser<\/code> verifies that a post belongs to a user.<\/li>\n\n\n\n<li><code>testUserHasManyPosts<\/code> confirms that a user can have multiple posts.<\/li>\n\n\n\n<li><code>testDeletingUserDeletesPosts<\/code> ensures that deleting a user also deletes all their posts.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Testing relationships like these can help catch issues early, making your application more robust and easier to maintain.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By incorporating these advanced techniques into your daily work, you&#8217;re not just coding; you&#8217;re crafting applications with attention to detail, efficiency, and maintainability.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction Eloquent is an Object-Relational Mapping (ORM) included with Laravel, one of the most popular PHP frameworks. It provides a beautiful, simple ActiveRecord implementation for working with your database. With Eloquent, you can manage complex database interactions using a more expressive and more maintainable syntax. Gone are the days of writing raw SQL queries; with [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_genesis_hide_title":false,"_genesis_hide_breadcrumbs":false,"_genesis_hide_singular_image":false,"_genesis_hide_footer_widgets":false,"_genesis_custom_body_class":"","_genesis_custom_post_class":"","_genesis_layout":"","_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[20,4],"tags":[],"class_list":["post-1130","post","type-post","status-publish","format-standard","category-php","category-programming-languages","entry"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.6 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Advanced Laravel Eloquent Techniques<\/title>\n<meta name=\"description\" content=\"Eloquent is an Object-Relational Mapping (ORM) included with Laravel, one of the most popular PHP frameworks. It provides a ActiveRecord\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.w3computing.com\/articles\/advanced-laravel-eloquent-techniques\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Advanced Laravel Eloquent Techniques\" \/>\n<meta property=\"og:description\" content=\"Eloquent is an Object-Relational Mapping (ORM) included with Laravel, one of the most popular PHP frameworks. It provides a ActiveRecord\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.w3computing.com\/articles\/advanced-laravel-eloquent-techniques\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-08-29T05:12:50+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-08-29T05:27:57+00:00\" \/>\n<meta name=\"author\" content=\"w3compadmin\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"w3compadmin\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"25 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"TechArticle\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/advanced-laravel-eloquent-techniques\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/advanced-laravel-eloquent-techniques\\\/\"},\"author\":{\"name\":\"w3compadmin\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#\\\/schema\\\/person\\\/a550b3e20d78bb4f79b7c6b7b53f0561\"},\"headline\":\"Advanced Laravel Eloquent Techniques\",\"datePublished\":\"2023-08-29T05:12:50+00:00\",\"dateModified\":\"2023-08-29T05:27:57+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/advanced-laravel-eloquent-techniques\\\/\"},\"wordCount\":5649,\"commentCount\":0,\"articleSection\":[\"PHP\",\"Programming Languages\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/advanced-laravel-eloquent-techniques\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/advanced-laravel-eloquent-techniques\\\/\",\"url\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/advanced-laravel-eloquent-techniques\\\/\",\"name\":\"Advanced Laravel Eloquent Techniques\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#website\"},\"datePublished\":\"2023-08-29T05:12:50+00:00\",\"dateModified\":\"2023-08-29T05:27:57+00:00\",\"author\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#\\\/schema\\\/person\\\/a550b3e20d78bb4f79b7c6b7b53f0561\"},\"description\":\"Eloquent is an Object-Relational Mapping (ORM) included with Laravel, one of the most popular PHP frameworks. It provides a ActiveRecord\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/advanced-laravel-eloquent-techniques\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/advanced-laravel-eloquent-techniques\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/advanced-laravel-eloquent-techniques\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Articles Home\",\"item\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Programming Languages\",\"item\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/programming-languages\\\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Advanced Laravel Eloquent Techniques\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#website\",\"url\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/\",\"name\":\"Developer Articles Hub\",\"description\":\"\",\"alternateName\":\"Developer Articles\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/#\\\/schema\\\/person\\\/a550b3e20d78bb4f79b7c6b7b53f0561\",\"name\":\"w3compadmin\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/wp-content\\\/litespeed\\\/avatar\\\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266\",\"url\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/wp-content\\\/litespeed\\\/avatar\\\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266\",\"contentUrl\":\"https:\\\/\\\/www.w3computing.com\\\/articles\\\/wp-content\\\/litespeed\\\/avatar\\\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266\",\"caption\":\"w3compadmin\"},\"sameAs\":[\"http:\\\/\\\/w3computing.com\\\/articles\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Advanced Laravel Eloquent Techniques","description":"Eloquent is an Object-Relational Mapping (ORM) included with Laravel, one of the most popular PHP frameworks. It provides a ActiveRecord","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.w3computing.com\/articles\/advanced-laravel-eloquent-techniques\/","og_locale":"en_US","og_type":"article","og_title":"Advanced Laravel Eloquent Techniques","og_description":"Eloquent is an Object-Relational Mapping (ORM) included with Laravel, one of the most popular PHP frameworks. It provides a ActiveRecord","og_url":"https:\/\/www.w3computing.com\/articles\/advanced-laravel-eloquent-techniques\/","article_published_time":"2023-08-29T05:12:50+00:00","article_modified_time":"2023-08-29T05:27:57+00:00","author":"w3compadmin","twitter_card":"summary_large_image","twitter_misc":{"Written by":"w3compadmin","Est. reading time":"25 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"TechArticle","@id":"https:\/\/www.w3computing.com\/articles\/advanced-laravel-eloquent-techniques\/#article","isPartOf":{"@id":"https:\/\/www.w3computing.com\/articles\/advanced-laravel-eloquent-techniques\/"},"author":{"name":"w3compadmin","@id":"https:\/\/www.w3computing.com\/articles\/#\/schema\/person\/a550b3e20d78bb4f79b7c6b7b53f0561"},"headline":"Advanced Laravel Eloquent Techniques","datePublished":"2023-08-29T05:12:50+00:00","dateModified":"2023-08-29T05:27:57+00:00","mainEntityOfPage":{"@id":"https:\/\/www.w3computing.com\/articles\/advanced-laravel-eloquent-techniques\/"},"wordCount":5649,"commentCount":0,"articleSection":["PHP","Programming Languages"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.w3computing.com\/articles\/advanced-laravel-eloquent-techniques\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.w3computing.com\/articles\/advanced-laravel-eloquent-techniques\/","url":"https:\/\/www.w3computing.com\/articles\/advanced-laravel-eloquent-techniques\/","name":"Advanced Laravel Eloquent Techniques","isPartOf":{"@id":"https:\/\/www.w3computing.com\/articles\/#website"},"datePublished":"2023-08-29T05:12:50+00:00","dateModified":"2023-08-29T05:27:57+00:00","author":{"@id":"https:\/\/www.w3computing.com\/articles\/#\/schema\/person\/a550b3e20d78bb4f79b7c6b7b53f0561"},"description":"Eloquent is an Object-Relational Mapping (ORM) included with Laravel, one of the most popular PHP frameworks. It provides a ActiveRecord","breadcrumb":{"@id":"https:\/\/www.w3computing.com\/articles\/advanced-laravel-eloquent-techniques\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.w3computing.com\/articles\/advanced-laravel-eloquent-techniques\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.w3computing.com\/articles\/advanced-laravel-eloquent-techniques\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Articles Home","item":"https:\/\/www.w3computing.com\/articles\/"},{"@type":"ListItem","position":2,"name":"Programming Languages","item":"https:\/\/www.w3computing.com\/articles\/programming-languages\/"},{"@type":"ListItem","position":3,"name":"Advanced Laravel Eloquent Techniques"}]},{"@type":"WebSite","@id":"https:\/\/www.w3computing.com\/articles\/#website","url":"https:\/\/www.w3computing.com\/articles\/","name":"Developer Articles Hub","description":"","alternateName":"Developer Articles","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.w3computing.com\/articles\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/www.w3computing.com\/articles\/#\/schema\/person\/a550b3e20d78bb4f79b7c6b7b53f0561","name":"w3compadmin","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.w3computing.com\/articles\/wp-content\/litespeed\/avatar\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266","url":"https:\/\/www.w3computing.com\/articles\/wp-content\/litespeed\/avatar\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266","contentUrl":"https:\/\/www.w3computing.com\/articles\/wp-content\/litespeed\/avatar\/bd481d404e42caa2763662a3bfe825f8.jpg?ver=1780141266","caption":"w3compadmin"},"sameAs":["http:\/\/w3computing.com\/articles"]}]}},"featured_image_src":null,"featured_image_src_square":null,"author_info":{"display_name":"w3compadmin","author_link":"https:\/\/www.w3computing.com\/articles\/author\/w3compadmin\/"},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/posts\/1130","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/comments?post=1130"}],"version-history":[{"count":5,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/posts\/1130\/revisions"}],"predecessor-version":[{"id":1135,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/posts\/1130\/revisions\/1135"}],"wp:attachment":[{"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/media?parent=1130"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/categories?post=1130"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.w3computing.com\/articles\/wp-json\/wp\/v2\/tags?post=1130"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}