Back

image
๐—ง๐—ถ๐—ฝ ๐—ผ๐—ณ ๐—ง๐—ต๐—ฒ ๐——๐—ฎ๐˜† ๐—ณ๐—ผ๐—ฟ ๐—Ÿ๐—ฎ๐—ฟ๐—ฎ๐˜ƒ๐—ฒ๐—น๐—ถ๐—ฎ๐—ป๐˜€โค๏ธ

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

3 โ€ข โ€ข

159

โ€ข
โ€ข
  • No matching results...
  • Searching...

/ 1000

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.

1 โ€ข โ€ข

51

โ€ข
โ€ข

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.

โ€ข โ€ข

66

โ€ข
โ€ข