Join us
@imjaykishan ã» Jul 24,2022 ã» 1 min read ã» 1390 views
This article will discuss one of the Querying advanced methods in Laravel that will save you time as well and also will be an optimized way of querying data.
Introduction
Laravel is one of the most used and most advanced frameworks ever developed in PHP, If you are here you must be already using it, So today we will discuss one of the Querying advanced methods in Laravel that will save you time as well and also will be an optimized way of querying data.
Local Scopes
It is a querying method in Laravel in which we can create a specific scope or you could say it is a function in a Model file that can query data that is used redundantly all over the project, let me simplify it with an example.
Suppose we want to query a User having status as 1 which means active and its email is verified
With this approach, if we want to query the same data in multiple Functions, we have to call it everywhere or we can create a function in the Model for this particular functionality. However, still, it will not be as generalized as Scopes are, now let's see the approach using Local Scope.
Firstly we have to declare the Local Scope in the Model in User.php
Then we can use this functions to filter out data in the controller
In this way, Code gets more readable and Optimised.
Bonus
There are some other types of scopes as well, we can use them according to requirements which are
Global Scope
After adding the scope in the example above to the App\Models\User
model, a call to the User::all()
the method will execute the following SQL query:
Dynamic Scope
This Scope is used when you have to pass any value to the function example
Usage
Conclusion
Now we know all about laravel local scopes I hope this helps in the optimization of your code, If found any confusion you can comment below, and if you like it. for more info on this, you can follow Laravel Documentation and share this article with those who need it.
Join other developers and claim your FAUN account now!
Influence
Total Hits
Posts
Only registered users can post comments. Please, login or signup.