Hello ?
Alright, let's talk about Query Scopes. They're awesome, they make queries much easier to read, no doubt about it. But there's one thing I hate about them: magic. And when you're working with a team where not everyone is a backend developer, it can make their lives miserable. Sure, you can add PHPDocs, but there’s always some magic going on. If you've never used scopes before, no worries, hang tight bud.
So, What Are Scopes? ?
Consider this code:
use App\Models\User; $users = User::query() ->where('votes', '>', 100); ->where('active', 1); ->orderBy('created_at') ->get();
This is how you would typically write queries. But when queries become too complex or hard to read, you can abstract them into scopes:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; class User extends Model { public function scopePopular(Builder $query): void { $query->where('votes', '>', 100); } public function scopeActive(Builder $query): void { $query->where('active', 1); } }
Now you can do this:
$users = User::query() ->popular() ->active() ->orderBy('created_at') ->get();
Reads much better right? I know. But the issue is, you don't get any autocompletion. This is dark magic to the IDE. Since scopes are resolved at runtime and prefixed with scope, there is no way your IDE knows about them unless you help it out.
One way is through PHPDocs, like so:
/** * @method static Builder popular() * @method static Builder active() */ class User extends Model
Another downside to scopes? The most frequently used models end up bloated with tons of them, for nothing. I love skimming through my models and immediately seeing the relationships and core logic, not a bunch of query abstractions.
Sooo? Do we just ditch scopes and move on? Well, that's an option, or you could use custom query builders.
Custom Query Builders ?
As the name suggests, a custom query builder let's you move all your query abstractions into a dedicated class. The code will be more organized in a way.
Let's create a new class UserQueryBuilder:
<?php namespace App\Eloquent\QueryBuilders; use App\Models\User; use Illuminate\Database\Eloquent\Builder; class UserQueryBuilder extends Builder { public function popular(): self { return $this->where('votes', '>', 100); } public function active(): self { return $this->where('active', 1); } }
Where to put builders? There is no guideline, but I personally like to place them in app/Eloquent/QueryBuilders.
Now let's use this builder in the User model:
<?php namespace App\Models; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; class User extends Model { public function newEloquentBuilder($query): UserQueryBuilder { return new UserQueryBuilder($query); } // for type hints public static function query(): UserQueryBuilder { return parent::query(); } }
And just like that, you can now do:
$users = User::query() ->popular() ->active() ->orderBy('created_at') ->get();
Works exactly the same, and you get full autocompletion. Plus, code navigation works perfectly, it takes you where you need to be ?
Another cool thing is you can dynamically resolve query builders if needed.
public function newEloquentBuilder($query): UserQueryBuilder { if ($this->status === State::Pending) { return new PendingUserQueryBuilder($query); // extends UserQueryBuilder } return new UserQueryBuilder($query); }
This way you avoid having one big query builder when you can group queries by context (like a state).
That's it ✅
Scopes are cool, and if I only have 2-3 of them, I'll stick with them. But when things start to get out of hand, custom query builders are the way to go. They are worth the extra effort, keeping your code clean, organized, and easier to maintain ?
The above is the detailed content of Laravel Custom Query Builders Over Scopes. For more information, please follow other related articles on the PHP Chinese website!

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
