当前位置: 首页 > 软件库 > Web应用开发 > Web框架 >

laravel-collection-macros

A set of useful Laravel collection macros
授权协议 MIT License
开发语言 PHP
所属分类 Web应用开发、 Web框架
软件类型 开源软件
地区 不详
投 递 者 路伟
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

A set of useful Laravel collection macros

Run testsCheck & fix styling

This repository contains some useful collection macros.

Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can pull in the package via composer:

composer require spatie/laravel-collection-macros

The package will automatically register itself.

Macros

after

Get the next item from the collection.

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

$currentItem = 2;

$currentItem = $collection->after($currentItem); // return 3;
$collection->after($currentItem); // return null;

$currentItem = $collection->after(function($item) {
    return $item > 1;
}); // return 3;

You can also pass a second parameter to be used as a fallback.

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

$currentItem = 3;

$collection->after($currentItem, $collection->first()); // return 1;

at

Retrieve an item at an index.

$data = new Collection([1, 2, 3]);

$data->at(0); // 1
$data->at(1); // 2
$data->at(-1); // 3

second

Retrieve item at the second index.

$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

$data->second(); // 2

third

Retrieve item at the third index.

$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

$data->third(); // 3

fourth

Retrieve item at the fourth index.

$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

$data->fourth(); // 4

fifth

Retrieve item at the fifth index.

$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

$data->fifth(); // 5

sixth

Retrieve item at the sixth index.

$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

$data->sixth(); // 6

seventh

Retrieve item at the seventh index.

$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

$data->seventh(); // 7

eighth

Retrieve item at the eighth index.

$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

$data->eighth(); // 8

ninth

Retrieve item at the ninth index.

$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

$data->ninth(); // 9

tenth

Retrieve item at the tenth index.

$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

$data->tenth(); // 10

getNth

Retrieve item at the nth item.

$data = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);

$data->getNth(); // 11

before

Get the previous item from the collection.

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

$currentItem = 2;

$currentItem = $collection->before($currentItem); // return 1;
$collection->before($currentItem); // return null;

$currentItem = $collection->before(function($item) {
    return $item > 2;
}); // return 2;

You can also pass a second parameter to be used as a fallback.

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

$currentItem = 1;

$collection->before($currentItem, $collection->last()); // return 3;

catch

See Try

chunkBy

Chunks the values from a collection into groups as long the given callback is true. If the optional parameter $preserveKeys as true is passed, it will preserve the original keys.

collect(['A', 'A', 'B', 'A'])->chunkBy(function($item) {
    return $item == 'A';
}); // return Collection([['A', 'A'],['B'], ['A']])

collectBy

Get an item at a given key, and collect it.

$collection = collect([
    'foo' => [1, 2, 3],
    'bar' => [4, 5, 6],
]);

$collection->collectBy('foo'); // Collection([1, 2, 3])

You can also pass a second parameter to be used as a fallback.

$collection = collect([
    'foo' => [1, 2, 3],
    'bar' => [4, 5, 6],
]);

$collection->collectBy('baz', ['Nope']); // Collection(['Nope'])

eachCons

Get the following consecutive neighbours in a collection from a given chunk size. If the optional parameter $preserveKeys as true is passed, it will preserve the original keys.

collect([1, 2, 3, 4])->eachCons(2); // return collect([[1, 2], [2, 3], [3, 4]])

extract

Extract keys from a collection. This is very similar to only, with two key differences:

  • extract returns an array of values, not an associative array
  • If a value doesn't exist, it will fill the value with null instead of omitting it

extract is useful when using PHP 7.1 short list() syntax.

[$name, $role] = collect($user)->extract('name', 'role.name');

filterMap

Map a collection and remove falsy values in one go.

$collection = collect([1, 2, 3, 4, 5, 6])->filterMap(function ($number) {
    $quotient = $number / 3;

    return is_integer($quotient) ? $quotient : null;
});

$collection->toArray(); // returns [1, 2]

firstOrFail

Get the first item. Throws Spatie\CollectionMacros\Exceptions\CollectionItemNotFound if the item was not found.

$collection = collect([1, 2, 3, 4, 5, 6])->firstOrFail();

$collection->toArray(); // returns [1]

collect([])->firstOrFail(); // throws Spatie\CollectionMacros\Exceptions\CollectionItemNotFound

firstOrPush

Retrieve the first item using the callable given as the first parameter. If no value exists, push the value of the secondparameter into the collection. You can pass a callable as the second parameter.

This method is really useful when dealing with cached class properties, where you want to store a value retrieved from an API or computationally expensive function in a collection to be used multiple times.

$collection = collect([1, 2, 3])->firstOrPush(fn($item) => $item === 4, 4);

$collection->toArray(); // returns [1, 2, 3, 4]

Occasionally, you'll want to specify the target collection to be pushed to. You may pass this as a third parameter.

$collection = collect([1, 2, 3]);
$collection->filter()->firstOrPush(fn($item) => $item === 4, 4, $collection);

$collection->toArray(); // returns [1, 2, 3, 4]

fromPairs

Transform a collection into an associative array form collection item.

$collection = collect([['a', 'b'], ['c', 'd'], ['e', 'f']])->fromPairs();

$collection->toArray(); // returns ['a' => 'b', 'c' => 'd', 'e' => 'f']

glob

Returns a collection of a glob() result.

Collection::glob('config/*.php');

groupByModel

Similar to groupBy, but groups the collection by an Eloquent model. Since the key is an object instead of an integer or string, the results are divided into separate arrays.

$posts->groupByModel('category');

// [
//     [$categoryA, [/*...$posts*/]],
//     [$categoryB, [/*...$posts*/]],
// ];

Full signature: groupByModel($callback, $preserveKeys, $modelKey, $itemsKey)

head

Retrieves first item from the collection.

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

$collection->head(); // return 1

$collection = collect([]);

$collection->head(); // return null

ifAny

Executes the passed callable if the collection isn't empty. The entire collection will be returned.

collect()->ifAny(function(Collection $collection) { // empty collection so this won't get called
   echo 'Hello';
});

collect([1, 2, 3])->ifAny(function(Collection $collection) { // non-empty collection so this will get called
   echo 'Hello';
});

ifEmpty

Executes the passed callable if the collection is empty. The entire collection will be returned.

collect()->ifEmpty(function(Collection $collection) { // empty collection so this will called
   echo 'Hello';
});

collect([1, 2, 3])->ifEmpty(function(Collection $collection) { // non-empty collection so this won't get called
   echo 'Hello';
});

insertAt

Inserts an item at a given index and returns the updated Collection instance. Optionally a key can be given.

collect(['zero', 'two', 'three'])->insertAt(1, 'one');
// Collection contains ['zero', 'one', 'two', 'three']

collect(['zero' => 0, 'two' => 2, 'three' => 3]->insertAt(1, 5, 'five');
// Collection contains ['zero' => 0, 'five' => 5, 'two' => 2, 'three' => 3]

none

Checks whether a collection doesn't contain any occurrences of a given item, key-value pair, or passing truth test. The function accepts the same parameters as the contains collection method.

collect(['foo'])->none('bar'); // returns true
collect(['foo'])->none('foo'); // returns false

collect([['name' => 'foo']])->none('name', 'bar'); // returns true
collect([['name' => 'foo']])->none('name', 'foo'); // returns false

collect(['name' => 'foo'])->none(function ($key, $value) {
   return $key === 'name' && $value === 'bar';
}); // returns true

paginate

Create a LengthAwarePaginator instance for the items in the collection.

collect($posts)->paginate(5);

This paginates the contents of $posts with 5 items per page. paginate accepts quite some options, head over to the Laravel docs for an in-depth guide.

paginate(int $perPage = 15, string $pageName = 'page', int $page = null, int $total = null, array $options = [])

parallelMap

Identical to map but each item in the collection will be processed in parallel. Before using this macro you should pull in the amphp/parallel-functions package.

composer require amphp/parallel-functions

Be aware that under the hood some overhead is introduced to make the parallel processing possible. When your $callable is only a simple operation it's probably better to use map instead. Also keep in mind that parallelMap can be memory intensive.

$pageSources = collect($urls)->parallelMap(function($url) {
    return file_get_contents($url);
});

The page contents of the given $urls will be fetched at the same time. The underlying amp sets a maximum of 32 concurrent processes by default.

There is a second (optional) parameter, through which you can define a custom parallel processing pool. It looks like this:

use Amp\Parallel\Worker\DefaultPool;

$pool = new DefaultPool(8);

$pageSources = collect($urls)->parallelMap(function($url) {
    return file_get_contents($url);
}, $pool);

If you don't need to extend the worker pool, or can't be bothered creating the new pool yourself; you can use an integer the the number of workers you'd like to use. A new DefaultPool will be created for you:

$pageSources = collect($urls)->parallelMap(function($url) {
    return file_get_contents($url);
}, 8);

This helps to reduce the memory overhead, as the default worker pool limit is 32 (as defined in amphp/parallel). Using fewer worker threads can significantly reduce memory and processing overhead, in many cases. Benchmark and customise the worker thread limit to suit your particular use-case.

pluckMany

Returns a collection with only the specified keys.

$collection = collect([
    ['a' => 1, 'b' => 10, 'c' => 100],
    ['a' => 2, 'b' => 20, 'c' => 200],
]);

$collection->pluckMany(['a', 'b']);

// returns
// collect([
//     ['a' => 1, 'b' => 10],
//     ['a' => 2, 'b' => 20],
// ]);

pluckToArray

Returns array of values of a given key.

$collection = collect([
    ['a' => 1, 'b' => 10],
    ['a' => 2, 'b' => 20],
    ['a' => 3, 'b' => 30]
]);

$collection->pluckToArray('a'); // returns [1, 2, 3]

prioritize

Move elements to the start of the collection.

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

$collection
   ->prioritize(function(array $item) {
      return $item['id'] === 2;
   })
   ->pluck('id')
   ->toArray(); // returns [2, 1, 3]

rotate

Rotate the items in the collection with given offset

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

$rotate = $collection->rotate(1);

$rotate->toArray();

// [2, 3, 4, 5, 6, 1]

sectionBy

Splits a collection into sections grouped by a given key. Similar to groupBy but respects the order of the items in the collection and reuses existing keys.

$collection = collect([
    ['name' => 'Lesson 1', 'module' => 'Basics'],
    ['name' => 'Lesson 2', 'module' => 'Basics'],
    ['name' => 'Lesson 3', 'module' => 'Advanced'],
    ['name' => 'Lesson 4', 'module' => 'Advanced'],
    ['name' => 'Lesson 5', 'module' => 'Basics'],
]);

$collection->sectionBy('module');

// [
//     ['Basics', [
//         ['name' => 'Lesson 1', 'module' => 'Basics'],
//         ['name' => 'Lesson 2', 'module' => 'Basics'],
//     ]],
//     ['Advanced', [
//         ['name' => 'Lesson 3', 'module' => 'Advanced'],
//         ['name' => 'Lesson 4', 'module' => 'Advanced'],
//     ]],
//     ['Basics', [
//         ['name' => 'Lesson 5', 'module' => 'Basics'],
//     ]],
// ];

Full signature: sectionBy($callback, $preserveKeys, $sectionKey, $itemsKey)

simplePaginate

Create a Paginator instance for the items in the collection.

collect($posts)->simplePaginate(5);

This paginates the contents of $posts with 5 items per page. simplePaginate accepts quite some options, head over to the Laravel docs for an in-depth guide.

simplePaginate(int $perPage = 15, string $pageName = 'page', int $page = null, int $total = null, array $options = [])

For a in-depth guide on pagination, check out the Laravel docs.

sliceBefore

Slice the values out from a collection before the given callback is true. If the optional parameter $preserveKeys as true is passed, it will preserve the original keys.

collect([20, 51, 10, 50, 66])->sliceBefore(function($item) {
    return $item > 50;
}); // return collect([[20],[51, 10, 50], [66])

tail

Extract the tail from a collection. So everything except the first element. It's a shorthand for slice(1)->values(), but nevertheless very handy. If the optional parameter $preserveKeys as true is passed, it will preserve the keys and fallback to slice(1).

collect([1, 2, 3])->tail(); // return collect([2, 3])

toPairs

Transform a collection into an array with pairs.

$collection = collect(['a' => 'b', 'c' => 'd', 'e' => 'f'])->toPairs();

$collection->toArray(); // returns ['a', 'b'], ['c', 'd'], ['e', 'f']

transpose

The goal of transpose is to rotate a multidimensional array, turning the rows into columns and the columns into rows.

collect([
    ['Jane', 'Bob', 'Mary'],
    ['jane@example.com', 'bob@example.com', 'mary@example.com'],
    ['Doctor', 'Plumber', 'Dentist'],
])->transpose()->toArray();

// [
//     ['Jane', 'jane@example.com', 'Doctor'],
//     ['Bob', 'bob@example.com', 'Plumber'],
//     ['Mary', 'mary@example.com', 'Dentist'],
// ]

try

If any of the methods between try and catch throw an exception, then the exception can be handled in catch.

collect(['a', 'b', 'c', 1, 2, 3])
    ->try()
    ->map(fn ($letter) => strtoupper($letter))
    ->each(function() {
        throw new Exception('Explosions in the sky');
    })
    ->catch(function (Exception $exception) {
        // handle exception here
    })
    ->map(function() {
        // further operations can be done, if the exception wasn't rethrow in the `catch`
    });

While the methods are named try/catch for familiarity with PHP, the collection itself behaves more like a database transaction. So when an exception is thrown, the original collection (before the try) is returned.

You may gain access to the collection within catch by adding a second parameter to your handler. You may also manipulate the collection within catch by returning a value.

$collection = collect(['a', 'b', 'c', 1, 2, 3])
    ->try()
    ->map(function ($item) {
        throw new Exception();
    })
    ->catch(function (Exception $exception, $collection) {
        return collect(['d', 'e', 'f']);
    })
    ->map(function ($item) {
        return strtoupper($item);
    });

// ['D', 'E', 'F']

validate

Returns true if the given $callback returns true for every item. If $callback is a string or an array, regard it as a validation rule.

collect(['foo', 'foo'])->validate(function ($item) {
   return $item === 'foo';
}); // returns true


collect(['sebastian@spatie.be', 'bla'])->validate('email'); // returns false
collect(['sebastian@spatie.be', 'freek@spatie.be'])->validate('email'); // returns true

withSize

Create a new collection with the specified amount of items.

Collection::withSize(1)->toArray(); // return [1];
Collection::withSize(5)->toArray(); // return [1,2,3,4,5];

Changelog

Please see CHANGELOG for more information what has changed recently.

Testing

$ composer test

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email freek@spatie.be instead of using the issue tracker.

Credits

About Spatie

Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.

License

The MIT License (MIT). Please see License File for more information.

  • 很多时候查询结果需要用 Collection 处理后再分页,而 Laravel 中是不支持的。 下面稍作修改,来实现上面的需求 集合处理查询结果 $users = DB::table('users') ->get() ->each(function($item, $key){ $item->total = 11; })->pa

  • 1、简介   Illuminate\Support\Collection类为处理数组数据提供了平滑、方便的封装。例如,查看下面的代码,我们使用帮助函数collect创建一个新的集合实例,为每一个元素运行strtoupper函数,然后移除所有空元素: $collection = collect(['taylor', 'abigail', null])->map(function ($name) {

  • 我的个人博客:逐步前行STEP 1、first 返回集合第一个通过指定测试的元素: collect([1, 2, 3, 4])->first(); // 1 collect([1, 2, 3, 4])->first(function ($value, $key) { return $value > 2; }); // 3 2、last 返回集合中,最后一个通过指定测试的元素: co

  • 一、预备知识 Laravel Macroable 的使用需要对php闭包的相关知识有所了解,可以参看文档 php 闭包 二、代码分析 Laravel Macroable 源码对应 \Illuminate\Support\Traits\Macroable 这个trait 文件,这里将其代码剥离出来单独运行、测试,以便研究。 其源码如下 // Macroable.php <?php trait M

  • ## Laravel学习笔记汇总——Collection方法详解 本文参考:https:// laravel.com/docs/8.x/collections // 返回整个底层的数组 collect([1, 2, 3])->all();  // [1, 2, 3] // 返回平均数 $average = collect([1, 1, 2, 4])->avg(); # 也可以用全拼average

  • 1.map方法:返回回调函数中返回的结果 // 遍历整个集合并将每一个数值传入给定的回调函数: $multiplied = $collection->map(function ($item, $key) { return $item * 2; }); 2.each方法:在原集合基础上附加一些数据。 // 遍历集合中的项目,并将之传入给定的回调函数: $collection = $coll

  • 一.背景: 业务开发对二维数组频繁操作,故总结一下好用的collection方法。 原本数据结构: Illuminate\Database\Eloquent\Collection {#2988 all: [ App\Model\NotifyModel {#3009 notify_id: 1, user_id: 1, co

  • // 创建集合 collect([1, 2, 3]); // 返回该集合所代表的底层数组: $collection->all(); // 返回集合中所有项目的平均值: collect([1, 1, 2, 4])->avg() // 2 $collection->average(); // 将集合拆成多个给定大小的较小集合: collect([1, 2, 3, 4, 5])->chunk(2); /

  • 今天在使用laravel的时候碰到个问题,我在模型里面使用了修改器,把type对应的数字变成了显示的中文,像下面这样: 1、collection的坑 public function getTypeAttribute($value) { $labelType = [ 1 => '个性', 2 => '风格', 3 => '用户评论标签', ]; return $labe

  • 十五个常用的 Laravel 集合(Collection) Laravel Eloquent 通常返回一个集合作为结果,集合包含很多有用的、功能强大的方法。你可以很方便的对集合进行过滤、修改等操作。本次教程就一起来看一看集合的常用方法及功能。 集合并不仅限于 eloquent ,也可以单独使用。但 Eloquent 的结果就是一个集合。你可以使用助手函数 collect 将数组转化为集合。下面所列

  • 场景:        项目迁移后 初始化角色的权限 案列解析:        代替了array_filter, 没啥必要性不这样话的也可以的          Collection::macro('forOperator', function() { return $this->filter(function ($value) { return preg_match(

  • 简介 Illuminate\Support\Collection 类提供了一个更具可读性的、更便于处理数组数据的封装。 具体例子看下面的代码。我们使用了 collect 函数从数组中创建新的集合实例,对其中的每个元素运行 strtoupper 函数之后再移除所有的空元素: $collection = collect(['taylor', 'abigail', null])->map(functio

  • 我们知道,在laravel框架中使用 Eloquent 模型来查询数据库返回的是 Collection对象,但是我们却可以调用 json_encode 来将其内容转换成 json 串,要知道普通的对象是没法做到这一点的。 相关的文件 Illuminate\Database\Eloquent\Collection.php Illuminate\Support\Collection.php 根本原理

  • laravel的Collection工具类对php的数组处理函数进行了封装,开发者可以链式调用Collection中的方法,从而优雅地处理数组类的数据。 <?php namespace Illuminate\Support; use ArrayAccess; use ArrayIterator; use Illuminate\Support\Traits\EnumeratesValues; u

  • 'address_list' =>$item->address()->get()->filter(function ($item) use($city){ return $item->city == $city; })->values() 不加 values() 键值不会改变 可能为  1,3,4,6....这样 , 直接返回前端 会报错    vue.runtime.esm.j

  • laravel 集合Collection 给 PHP 数组插上翅膀 转载于:https://www.cnblogs.com/mg007/p/11095411.html

 相关资料
  • 问题内容: 我该如何总结一个渴望加载的数据集? 这是我的表结构: 这些是我的模型/关系: 这是我的控制器 这是返回的数据的样子(以json格式,我理解雄辩的集合中的$ regions):- 我不知道如何将“交易”(4)的总和发送回视图? 问题答案: $deals = $regions->sum(function ($region) { return $region->submits->sum(‘d

  • 我通常会用能言善辩的拉雷维尔分别选择我的物品 我得到的是一个照明\数据库\雄辩\收藏与一个项目。后来我把它们放在一个数组中,这样我就有了这些照明\数据库\雄辩\集合对象的数组。 然而,有时我需要更多,所以我会这样做: 这是一个包含多个项目的集合。有没有一个简单的方法来改变一个照明\数据库\雄辩\集合的数组中的几个项目与单项照明\数据库\雄辩\集合? 我当然能做到: 但再次从DB中选择似乎是一个相当

  • // 创建集合 collect([1, 2, 3]); // 返回该集合所代表的底层数组: $collection->all(); // 返回集合中所有项目的平均值: $collection->avg(); // 将集合拆成多个给定大小的较小集合: $collection->chunk(4); // 将多个数组组成的集合折成单一数组集合: $collection->collapse(); // 用

  • 采集 采集模块是可以批量采集目标网站内容入库 下载安装 采集流程 ★ 添加采集点,填写采集规则 ★ 采集网址,采集内容 ★ 发布内容到指定栏目 1、下载安装 从ZTBCMS 模块->模块->模块仓库 中找到采集模块,点击下载。 下载完成后,解压出来,并命名为“Collection”,然后将它copy至项目目录中。 接着在后台本地模块中进行安装。 2、采集流程 位置:内容>内容管理>采集管理 采集流

  • 几种常用的键值对类型的数据结构 Installing NPM 安装:npm install d3-collection, 还可以下载最新版,此外还可以直接从 d3js.org 以 单独的标准库 或作为 D3 4.0 的一部分引入,支持 AMD, CommonJS 以及 vanilla 环境, 使用标签引入会暴露 d3 全局变量: <script src="https://d3js.org/d3-c