Query Scopes in laravel

laravel

Sharing is caring!

Applying conditions to queries gives you to power to retrieve and present filtered data in every imaginable manner. Some of these conditions will be used more than others, and Laravel provides a solution for cleanly packaging these conditions into easily readable and reusable statements, known as a scope. In this tutorial I’ll show you how to easily integrate scopes into your Laravel models.

Consider a filter that only retrieves completed list tasks. You could use the following where condition to retrieve those tasks:

You might however wish to use a query such as this at multiple locations throughout an application. If so, you can DRY the code up a bit by instead using a scope. A scope is just a convenience method you can add to your model which encapsulates the syntax used to execute a query such as the above. Scopes are defined by prefixing the name of a method with scope, as demonstrated here:

With the scope defined, you can execute it like so:

Here we can re-use query logic to encapsulate the database logic inside the model class methods.

For example if you have model called posts.php and if u have 3 types of post status fields called published,private,draft.

To get all the published posts :

Example:

How to pass parameters to scope:

Sharing is caring!