Học Laravel – Bài 39: Laravel Collections

Giới thiệu Collections trong Laravel:

Laravel Illuminate\Support\Collection cung cấp cách xử lý thuận tiện với dữ liệu mảng. Ví dụ sau sử dụng helper collect để tạo 1 collection instance từ array, chạy strtoupper lên mỗi element, và xóa những empty element:

$collection = collect(['taylor', 'abigail', null])->map(function (?string $name) {
    return strtoupper($name);
})->reject(function (string $name) {
    return empty($name);
});

Tạo Collections:

Helper collect trả về 1 instance của Illuminate\Support\Collection:

$collection = collect([1, 2, 3]);

Lưu ý: kết quả của query Eloquent cũng trả về 1 Collection instance.

Extend Collections:

Collection cũng cho phép bạn thêm các method bổ sung vào class Collection tại run time. Method macro nhận 1 closure mà sẽ được thực thi khi macro được gọi. Closure có thể tiếp cận các method khác của collection thông qua $this. Ví dụ, đoạn code sau thêm 1 method toUpper vào Collection class:

use Illuminate\Support\Collection;
use Illuminate\Support\Str;
 
Collection::macro('toUpper', function () {
    return $this->map(function (string $value) {
        return Str::upper($value);
    });
});
 
$collection = collect(['first', 'second']);
 
$upper = $collection->toUpper();
 
// ['FIRST', 'SECOND']

Thông thường bạn có thể define macro trong boot của service provider.

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *