{"id":610,"date":"2019-06-14T09:16:41","date_gmt":"2019-06-14T09:16:41","guid":{"rendered":"https:\/\/studysection.com\/blog\/?p=610"},"modified":"2019-06-14T10:06:09","modified_gmt":"2019-06-14T10:06:09","slug":"query-scopes-in-laravel","status":"publish","type":"post","link":"https:\/\/studysection.com\/blog\/query-scopes-in-laravel\/","title":{"rendered":"Query Scopes In Laravel"},"content":{"rendered":"<p><strong>Introduction:-<\/strong><br \/>\nLaravel has a powerful feature named query scopes. It is one of the many arrows in its quiver. Query scope is used to retrieve and filter the data in a comfortable way reducing the headache of the user. Eloquent ORM included with Laravel provides a number of ways to work with the database and query scopes come under this category. Generally, every table has a model in Laravel except pivot table which is optional and we use query scopes in that model or can define query scope in other file and can include it in the model.<\/p>\n<p><strong>Why we need Query Scopes:-<\/strong><br \/>\nSuppose the user has to fetch the posts and display it on various pages whether based on tags, categories, user search records. The common requirement of all these posts should be that all posts should be active i.e. there status should be set to 1 in the database in order to get displayed on the website. So, the user is left with two choices either to apply status check query on all posts i.e. <\/p>\n<pre>$posts = Post::where('status', '=' , 1)->get(); <\/pre>\n<p>or<br \/>\nto use a query scope where this status check condition is not needed to be implemented.<\/p>\n<p><strong>Query Scope Types:-<\/strong><br \/>\nThere are two types of query scopes in Laravel:-<\/p>\n<li>Global Scopes<\/li>\n<li>Local Scopes<\/li>\n<p>User can decide which Query Scope to use depending on the requirements.<\/p>\n<p><strong>Global Scopes:-<\/strong> Global Scopes is used when you want to apply certain constraints to all queries automatically. There are two ways to use global scopes.<br \/>\n<strong>First method<\/strong> &#8211; User can create a class which implements Illuminate\\Database\\Eloquent\\Scope interface. In this class, you are required to use one method named apply in which where constraints for the query are defined.<br \/>\n1. Create a file named ActiveScope in App Folder.<\/p>\n<pre>\r\n&lt:?php\r\n\r\nnamespace App\\Scopes;\r\n\r\nuse Illuminate\\Database\\Eloquent\\Scope;\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\nuse Illuminate\\Database\\Eloquent\\Builder;\r\n\r\nclass ActiveScope implements Scope\r\n{\r\n    \/**\r\n     * Apply the scope to a given Eloquent query builder.\r\n     *\r\n     * @param  \\Illuminate\\Database\\Eloquent\\Builder  $builder\r\n     * @param  \\Illuminate\\Database\\Eloquent\\Model  $model\r\n     * @return void\r\n     *\/\r\n    public function apply(Builder $builder, Model $model)\r\n    {\r\n        $builder->where('status', 1);\r\n    }\r\n}\r\n<\/pre>\n<p>2. Include this File in Required Model and override the boot method.<\/p>\n<pre>\r\n&lt;?php\r\n\r\nnamespace App;\r\n\r\nuse App\\Scopes\\ActiveScope;\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\n\r\nclass Post extends Model\r\n{\r\n    \/**\r\n     * The \"booting\" method of the model.\r\n     *\r\n     * @return void\r\n     *\/\r\n    protected static function boot()\r\n    {\r\n        parent::boot();\r\n\r\n        static::addGlobalScope(new ActiveScope);\r\n    }\r\n}\r\n<\/pre>\n<p>After that User has to add the query scope in the required model. User can use this scope in one than one model as per the requirement. After this, if the user executes the post query in <a href=\"https:\/\/www.studysection.com\/laravel-5.x-foundation\" style=\"color:blue\">laravel<\/a> it would automatically fetch all the posts whose status is 1 only.<\/p>\n<p>For e.g. <\/p>\n<pre>$posts = Post::all();<\/pre>\n<p>is similar to <\/p>\n<pre>$posts = Post::where('status', '=' , 1)->get();<\/pre>\n<p><strong>Second method<\/strong> &#8211; If the user wants to define a global query scope without creating a separate class that can also be done.<br \/>\n1. Define global query scope using closures in the model.<\/p>\n<pre>\r\n&lt;?php\r\n\r\nnamespace App;\r\n\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\nuse Illuminate\\Database\\Eloquent\\Builder;\r\n\r\nclass Post extends Model\r\n{\r\n    \/**\r\n     * The \"booting\" method of the model.\r\n     *\r\n     * @return void\r\n     *\/\r\n    protected static function boot()\r\n    {\r\n        parent::boot();\r\n\r\n        static::addGlobalScope('status', function (Builder $builder) {\r\n            $builder->where('status', 1);\r\n        });\r\n    }\r\n}\r\n<\/pre>\n<p>There may be some case arises when the user wants to get all posts irrespective of the status of the post in that case withoutGlobalScope method is used.<br \/>\nThis method is used when Scope is defined in a separate class. <\/p>\n<pre>Post::withoutGlobalScope(ActiveScope::class)->get();<\/pre>\n<p>This method is used when Global Scope is defined using closure.<\/p>\n<pre>Post::withoutGlobalScope('active')->get();<\/pre>\n<p><strong>Local Scopes:-<\/strong> In Local Query Scopes you can define constraints in the model and use in your website but it would not be automatically added to every query like global scope. You have to include it manually wherever this local scope is needed. It is useful to reduce the complexity of our query.<\/p>\n<p>For e.g.:- <\/p>\n<pre>\r\n&lt;?php\r\n\r\nnamespace App;\r\n\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\n\r\nclass Post extends Model\r\n{\r\n    \/**\r\n     * Scope a query to only show active posts.\r\n     *\r\n     * @param  \\Illuminate\\Database\\Eloquent\\Builder  $query\r\n     * @return \\Illuminate\\Database\\Eloquent\\Builder\r\n     *\/\r\n    public function scopeActive($query)\r\n    {\r\n        return $query->where(status,1);\r\n    }\r\n<\/pre>\n<p>Here to define a query scope a method named scopeActive is created. The method naming is important in this case as scope prefix is to be added in front and method name should be in camelCase and now to use this local scope:-<\/p>\n<pre>$posts = Post::active()->get();<\/pre>\n<p>Local Scope also includes dynamic scope which means to pass parameters to the scope method.<\/p>\n<pre>\r\n&lt;?php\r\n\r\nnamespace App;\r\n\r\nuse Illuminate\\Database\\Eloquent\\Model;\r\n\r\nclass Post extends Model\r\n{\r\n    \/**\r\n     * Scope a query to only include posts of a given status.\r\n     *\r\n     * @param  \\Illuminate\\Database\\Eloquent\\Builder  $query\r\n     * @param  mixed  $type\r\n     * @return \\Illuminate\\Database\\Eloquent\\Builder\r\n     *\/\r\n    public function scopeActive($query, $type)\r\n    {\r\n        return $query->where('status', $type);\r\n    }<\/pre>\n<p>Suppose there are three types of status in post table i.e. unapproved(where id =0), Approved(where id=1) and Rejected(id=2). So Instead of making three different methods you can define one method and can pass parameters as per the requirement. To get all rejected posts by admin use the following code:<\/p>\n<pre>$posts = Post::active(2)->get();<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Introduction:- Laravel has a powerful feature named query scopes. It is one of the many arrows in its quiver. Query<\/p>\n","protected":false},"author":1,"featured_media":619,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[6],"tags":[70,69,65,66,67,68,71],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v21.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>StudySection Blog - Query Scopes in Laravel Programming<\/title>\n<meta name=\"description\" content=\"Laravel has a powerful feature named query scopes. It is one of the many arrows in its quiver. Query scope is used to retrieve and filter the data.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/studysection.com\/blog\/query-scopes-in-laravel\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"StudySection Blog - Query Scopes in Laravel Programming\" \/>\n<meta property=\"og:description\" content=\"Laravel has a powerful feature named query scopes. It is one of the many arrows in its quiver. Query scope is used to retrieve and filter the data.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/studysection.com\/blog\/query-scopes-in-laravel\/\" \/>\n<meta property=\"og:site_name\" content=\"Blog Posts on famous people, innovations and educational topics\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/studysection\" \/>\n<meta property=\"article:published_time\" content=\"2019-06-14T09:16:41+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2019-06-14T10:06:09+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2019\/06\/laravel-blog.png\" \/>\n\t<meta property=\"og:image:width\" content=\"300\" \/>\n\t<meta property=\"og:image:height\" content=\"160\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"admin-studysection-blog\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@studysection\" \/>\n<meta name=\"twitter:site\" content=\"@studysection\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"admin-studysection-blog\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/studysection.com\/blog\/query-scopes-in-laravel\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/studysection.com\/blog\/query-scopes-in-laravel\/\"},\"author\":{\"name\":\"admin-studysection-blog\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402\"},\"headline\":\"Query Scopes In Laravel\",\"datePublished\":\"2019-06-14T09:16:41+00:00\",\"dateModified\":\"2019-06-14T10:06:09+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/studysection.com\/blog\/query-scopes-in-laravel\/\"},\"wordCount\":619,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/studysection.com\/blog\/#organization\"},\"keywords\":[\"code\",\"data\",\"laravel\",\"programming\",\"query\",\"scopes\",\"syntax\"],\"articleSection\":[\"Learn and Grow\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/studysection.com\/blog\/query-scopes-in-laravel\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/studysection.com\/blog\/query-scopes-in-laravel\/\",\"url\":\"https:\/\/studysection.com\/blog\/query-scopes-in-laravel\/\",\"name\":\"StudySection Blog - Query Scopes in Laravel Programming\",\"isPartOf\":{\"@id\":\"https:\/\/studysection.com\/blog\/#website\"},\"datePublished\":\"2019-06-14T09:16:41+00:00\",\"dateModified\":\"2019-06-14T10:06:09+00:00\",\"description\":\"Laravel has a powerful feature named query scopes. It is one of the many arrows in its quiver. Query scope is used to retrieve and filter the data.\",\"breadcrumb\":{\"@id\":\"https:\/\/studysection.com\/blog\/query-scopes-in-laravel\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/studysection.com\/blog\/query-scopes-in-laravel\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/studysection.com\/blog\/query-scopes-in-laravel\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/studysection.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Query Scopes In Laravel\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/studysection.com\/blog\/#website\",\"url\":\"https:\/\/studysection.com\/blog\/\",\"name\":\"Blog Posts on famous people, innovations and educational topics\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/studysection.com\/blog\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/studysection.com\/blog\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/studysection.com\/blog\/#organization\",\"name\":\"StudySection\",\"url\":\"https:\/\/studysection.com\/blog\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png\",\"contentUrl\":\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png\",\"width\":920,\"height\":440,\"caption\":\"StudySection\"},\"image\":{\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/studysection\",\"https:\/\/twitter.com\/studysection\",\"https:\/\/www.instagram.com\/study.section\/\",\"https:\/\/www.linkedin.com\/company\/studysection\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402\",\"name\":\"admin-studysection-blog\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g\",\"caption\":\"admin-studysection-blog\"},\"url\":\"https:\/\/studysection.com\/blog\/author\/admin-studysection-blog\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"StudySection Blog - Query Scopes in Laravel Programming","description":"Laravel has a powerful feature named query scopes. It is one of the many arrows in its quiver. Query scope is used to retrieve and filter the data.","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:\/\/studysection.com\/blog\/query-scopes-in-laravel\/","og_locale":"en_US","og_type":"article","og_title":"StudySection Blog - Query Scopes in Laravel Programming","og_description":"Laravel has a powerful feature named query scopes. It is one of the many arrows in its quiver. Query scope is used to retrieve and filter the data.","og_url":"https:\/\/studysection.com\/blog\/query-scopes-in-laravel\/","og_site_name":"Blog Posts on famous people, innovations and educational topics","article_publisher":"https:\/\/www.facebook.com\/studysection","article_published_time":"2019-06-14T09:16:41+00:00","article_modified_time":"2019-06-14T10:06:09+00:00","og_image":[{"width":300,"height":160,"url":"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2019\/06\/laravel-blog.png","type":"image\/png"}],"author":"admin-studysection-blog","twitter_card":"summary_large_image","twitter_creator":"@studysection","twitter_site":"@studysection","twitter_misc":{"Written by":"admin-studysection-blog","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/studysection.com\/blog\/query-scopes-in-laravel\/#article","isPartOf":{"@id":"https:\/\/studysection.com\/blog\/query-scopes-in-laravel\/"},"author":{"name":"admin-studysection-blog","@id":"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402"},"headline":"Query Scopes In Laravel","datePublished":"2019-06-14T09:16:41+00:00","dateModified":"2019-06-14T10:06:09+00:00","mainEntityOfPage":{"@id":"https:\/\/studysection.com\/blog\/query-scopes-in-laravel\/"},"wordCount":619,"commentCount":0,"publisher":{"@id":"https:\/\/studysection.com\/blog\/#organization"},"keywords":["code","data","laravel","programming","query","scopes","syntax"],"articleSection":["Learn and Grow"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/studysection.com\/blog\/query-scopes-in-laravel\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/studysection.com\/blog\/query-scopes-in-laravel\/","url":"https:\/\/studysection.com\/blog\/query-scopes-in-laravel\/","name":"StudySection Blog - Query Scopes in Laravel Programming","isPartOf":{"@id":"https:\/\/studysection.com\/blog\/#website"},"datePublished":"2019-06-14T09:16:41+00:00","dateModified":"2019-06-14T10:06:09+00:00","description":"Laravel has a powerful feature named query scopes. It is one of the many arrows in its quiver. Query scope is used to retrieve and filter the data.","breadcrumb":{"@id":"https:\/\/studysection.com\/blog\/query-scopes-in-laravel\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/studysection.com\/blog\/query-scopes-in-laravel\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/studysection.com\/blog\/query-scopes-in-laravel\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/studysection.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Query Scopes In Laravel"}]},{"@type":"WebSite","@id":"https:\/\/studysection.com\/blog\/#website","url":"https:\/\/studysection.com\/blog\/","name":"Blog Posts on famous people, innovations and educational topics","description":"","publisher":{"@id":"https:\/\/studysection.com\/blog\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/studysection.com\/blog\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/studysection.com\/blog\/#organization","name":"StudySection","url":"https:\/\/studysection.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png","contentUrl":"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png","width":920,"height":440,"caption":"StudySection"},"image":{"@id":"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/studysection","https:\/\/twitter.com\/studysection","https:\/\/www.instagram.com\/study.section\/","https:\/\/www.linkedin.com\/company\/studysection"]},{"@type":"Person","@id":"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402","name":"admin-studysection-blog","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/studysection.com\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g","caption":"admin-studysection-blog"},"url":"https:\/\/studysection.com\/blog\/author\/admin-studysection-blog\/"}]}},"views":959,"_links":{"self":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts\/610"}],"collection":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/comments?post=610"}],"version-history":[{"count":16,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts\/610\/revisions"}],"predecessor-version":[{"id":627,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts\/610\/revisions\/627"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/media\/619"}],"wp:attachment":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/media?parent=610"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/categories?post=610"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/tags?post=610"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}