๐ง๐ถ๐ฝ ๐ผ๐ณ ๐ง๐ต๐ฒ ๐๐ฎ๐ ๐ณ๐ผ๐ฟ ๐๐ฎ๐ฟ๐ฎ๐๐ฒ๐น๐ถ๐ฎ๐ป๐โค๏ธ
Laravel is amazing when it comes to simplifying data filtering and collection manipulation. Let's dive into an incredibly handy feature Laravel provides with collection methods! ๐๐ช
๐. ๐๐ก๐๐ญ ๐ข๐ฌ ๐๐๐ฉ๐ฉ๐๐ง๐ข๐ง๐ ?
๐ฟ๐ฒ๐ท๐ฒ๐ฐ๐(): Quickly excludes all items that match certain conditions.
๐. ๐๐ฌ๐ ๐๐๐ฌ๐
Imagine you want to manage a user list displaying only active members in your application dashboard. Using collection methods like ๐ฟ๐ฒ๐ท๐ฒ๐ฐ๐(), you can easily clean up your data without cluttering your codebase with loops or complex conditions.
Clean code, clearer logic!
#CodeTips
#Laravelians
#Laravel
#CleanCode
#WebDevelopment
#PHP
#BestPractices
This particular example would be better done as part of the query to avoid loading and hydrating every user in the database before filtering it down.
But there are definitely lots of use cases for collection methods that can't effectively be done as part of the query.
Yup! it's actually for those use-case. User::all() is just used for example.
Good tip! Just worth noting that this example is most effective when 'active' is a computed attribute rather than a database column.
If it's a DB column, using reject() would load the entire unfiltered collection first, which is less efficient than a simple User::where('active', true)->get().
Collection methods like reject() are really amazing when dealing with calculated attributes or complex logic that can't be easily translated to SQL.
Balancing Collection methods and Eloquent could be tricky.