Laravel gives you access to many useful methods that you can use to narrow the results of your Eloquent queries.
Occasionally you need to use the same conditions more than once. In that scenario, you can use scope. Let's look at how to add scopes to Laravel models easily.
Scopes is a feature of Laravel that lets you wrap your conditions into a reusable, simple statement. We'll demonstrate how easily you can add scopes to your Laravel models.
Imagine that you are making a to-do list application and that you need to get all completed tasks in different places. To retrieve all the tasks that have already been completed, you can use the following condition:
You may use the above condition more than once in your application. Laravel scopes can be used to make the code clean. The scope is just a method in your model that you can use to wrap up the syntax needed to run a query like the one above. Scopes are set by putting "scope " in front of the name of a method, as shown below.
With the scope mentioned above, you can do it this way:
On the other hand, if you want this scope to be dynamic and you want to get completed or not-completed to-dos, then you may pass an argument. Construct a parameter as you would for any other model method. This will allow you to get the to-dos based on your passing parameter to the method.
After you have specified the parameter, you may apply the scope in the following way:
You'll usually want to use scopes with relations. For example, you can get a list of a user's to-do items like the below:
When working with Laravel scopes, it is advisable to do so when you have several repeated queries and want to reuse the code.