😄Collections full (ok)

https://laravel.com/docs/9.x/collections#creating-collections

Bài tập 1: Xóa phần tử rỗng khỏi mảng

['taylor', 'abigail', null]

C:\xampp\htdocs\wpclidemo\app\Http\Controllers\HomeController.php

$collection = collect(['taylor', 'abigail', null])->map(function ($name) {
    return strtoupper($name);
  })->reject(function ($name) {
    return empty($name);
  });
  echo '<pre>';
    var_export($collection);
  echo '</pre>';
  die(" ");

Bài 2.1 : Extending Collections

C:\xampp\htdocs\wpclidemo\app\Http\Controllers\HomeController.php

Thông thường, bạn nên khai báo macro thu thập trong phương pháp khởi động của nhà cung cấp dịch vụ. https://laravel.com/docs/9.x/providers

Bài 2.2 Macro Arguments (Nếu cần, bạn có thể xác định các macro chấp nhận các đối số bổ sung:)

all()

avg()

chunk()

Thực hiện với view 👇

C:\xampp\htdocs\wpclidemo\app\Http\Controllers\HomeController.php

C:\xampp\htdocs\wpclidemo\resources\views\welcome.blade.php

chunkWhile()

Result 👇

collapse()

Result 👇

collect()

Result 👇

combine()

Result 👇

concat()

Result 👇

contains()

containsStrict() This method has the same signature as the contains method; however, all values are compared using "strict" comparisons.

Result 👇

Hoặc

Hoặc

Result 👇

count()

Result 👇

countBy()

crossJoin()

diff()

diffAssoc()

diffKeys()

doesntContain()

duplicates()

duplicatesStrict() This method has the same signature as the duplicates method; however, all values are compared using "strict" comparisons.

each()

eachSpread()

every()

😂If the collection is empty, the every method will return true:

except()

filter()

If no callback is supplied, all entries of the collection that are equivalent to false will be removed:

😒 For the inverse of filter, see the reject method.

reject()

first()

firstOrFail()

firstWhere()

flatMap()

flatten()

Hoặc

flip()

forget()

forPage()

get()

You may optionally pass a default value as the second argument:

You may even pass a callback as the method's default value. The result of the callback will be returned if the specified key does not exist:

groupBy()

Hoặc

Hoặc

has()

implode()

Hoặc

intersect()

intersectByKeys()

isEmpty()

isNotEmpty()

join()

keyBy()

Hoặc

keys()

last()

You may also call the last method with no arguments to get the last element in the collection. If the collection is empty, null is returned:

lazy()

macro()

make()

map()

mapInto()

mapSpread()

mapToGroups()

mapWithKeys()

max()

median()

merge()

Hoặc

mergeRecursive()

min()

mode()

nth()

Hoặc

only()

pad()

partition()

pipe()

pipeInto()

pipeThrough()

pluck()

Hoặc

Hoặc

Hoặc

pop()

Hoặc

prepend()

Hoặc

pull()

push()

put()

random()

Hoặc

range()

reduce()

Hoặc

Hoặc

Chú ý 😒😒😒

Result

reduceSpread()?? chưa hiểu??? 😒😒

reject()

replace()

replaceRecursive()

reverse()

search()

Hoặc

Hoặc

shift()

Hoặc

shuffle()

skip()

skipUntil()

Hoặc

skipWhile()

slice()

Hoặc

sliding()

Hoặc

sole()

Hoặc

Hoặc

sort()

sortBy()

Hoặc

Hoặc

Hoặc

Hoặc

sortDesc()

sortKeys()

sortKeysUsing()

splice()

Hoặc

split()

splitIn()

sum()

Hoặc

Hoặc

take()

Hoặc

takeUntil()

Hoặc

takeWhile()

times()

toArray()

toJson()

transform()

undot()

union()

unique()

Hoặc

Hoặc

unless()

Hoặc

unwrap()

value()

values()

when()

Hoặc

whenEmpty()

Hoặc

whenNotEmpty()

where()

Hoặc

whereBetween()

whereIn()

whereInstanceOf()

whereNotBetween()

whereNotIn()

whereNotNull()

whereNull()

wrap()

zip()

Higher Order Messages 😉😉😉 chưa hiểu?

Laravel: Understanding Collections’ Higher Order Messages

… and the beauty of them.

Photo by Karen Vardazaryan on Unsplash

If may think that enough tinkering around Laravel’s Collections too much have made you some kind of Collection expert, but Higher Order Messages are one level above in understanding.

One thing I couldn’t grasp, and probably you either if you are reading this, is how they work and what problem they try to solve, but falter not, these are relatively easy to understand when you think about them as proxies to the real methods.

Get off my lawn, you dirty closure!

Higher Order Messages are basically properties that act like you were doing a very short closure. To better exemplify, let’s say we want to filter all users who are not admin.

You can see that Mike and Abby are admins because the is_admin is true, so the first thing you could do to filter them should be to call the filter method of the Collection to return those who are inside another Collection instance.

While that line may work for some, we can make the filter a one line. The filter method as a Higher Order Message by the same name. It will take the value we are using to “get” as the what the closure should return for each item in the collection, being a property or an array key.

And that’s it, it’s very simple.

What about sum, for example?

Some methods do not return collections, and that’s fine. For example, the sum method returns the result of a sum on the value of each item.

In this case, we can sum the users who are admins:

We can make that whole call into one line, since the sum method actually does an additive operation in PHP which is compatible with booleans, where true is 1 and false is 0. So, yes, we can sum booleans without any problem.

Can you use methods? With arguments?

Higher Order Collection are also compatible with methods, including arguments to them. The method you pass will be used for each item, so let’s make an example.

This User class has a convenient method that returns true or false if the age is above to what we’re asking.

Let’s assume we have a collection of these User class instances. The old nasty way to filter them would be using a closure to execute on each of them.

And it gets more verbose when we have to include the age from a variable outside the closure.

But that can be, again, become a one line:

And that’s all folks!

Lazy Collection trong Laravel 6.0

1. Lazy Collection trong Laravel 6.0

Bài đăng này đã không được cập nhật trong 2 năm

Laravel 6.0 đã giới thiệu Lazy Collection. Lazy collection sử dụng PHP generators để cho phép chúng ta làm việc với một tập dữ liệu rất lớn và giữ cho mức sử dụng bộ nhớ ở mức thấp. Ví dụ với 60.000 bản ghi user. Nếu bây giờ chúng ta lấy ra tất cả các bản ghi cùng 1 lúc thì sao? Chúng ta nhận được lỗi 500 do quá tải bộ nhớ, bởi vì tất cả 60.000 user đều được tải vào bộ nhớ cùng lúc.

Và để loại bỏ việc sử dụng bộ nhớ này chúng ta sử dụng method cursor() . Method này cho phép chỉ thực hiện 1 câu truy vấn duy nhất và chỉ 1 Eloquent model được load ra tại 1 thời điểm .

Trong ví dụ này, việc gọi filter sẽ không được thực thi cho đến khi từng user được lặp lại, làm giảm đáng kể việc sử dụng bộ nhớ

Read Large File

Ngoài ra chúng ta có thể sử dụng lazy collection để đọc hàng GB khổng lồ. Method make() dùng để tạo 1 lazy collection class object

Ví dụ, chúng ta lấy 4 bản ghi với method chuck(), load các bản ghi vào LogEntry model và lặp qua các bản ghi đó.

Điểm chú ý ở đây chính là việc ta sử dụng hàm yield của php thay choreturn như Collection. Thay vì dừng thực thi hàm và trả về (return), yield trả về giá trị khi giá trị đó cần sử dụng đến mà không lưu trữ tất cả các giá trị trong bộ nhớ.

Ban có thể tìm hiểu thêm về yield tại đây

2. Tìm hiểu Lazy Collection

Last updated

Was this helpful?