Table of Contents
filter()
search()
chunk()
dump()
map()
zip()
whereNotIn()
max()
pluck()
each()
tap()
pipe()
contains()
forget()
avg()
Home PHP Framework Laravel 15 Awesome Laravel Collection Methods

15 Awesome Laravel Collection Methods

Dec 06, 2022 pm 08:44 PM
php laravel

15 Awesome Laravel Collection Methods

15 Awesome 15 Awesome Laravel Collection Methods Collection Methods Eloquent usually returns a collection as a result, which contains many useful and powerful methods. You can easily filter and modify the collection. In this tutorial, let’s take a look at the common methods and functions of collections.

Collection (collection) is not limited to eloquent and can also be used alone. But the result of Eloquent is a collection. You can use the helper function collect to convert an array into a collection. The collection methods listed below apply both to eloquent results and to the collection itself. [Related recommendations: laravel video tutorial]

For example, you have a post model. You found all posts in the php category.

$posts = App\Post::where('category', 'php')->get();
Copy after login

The above command returns a collection. Collection is a laravel class which uses array functions internally and adds many functionalities to them.

You can simply use the collect method to create a collection, as follows:

$collection = collect([
    [
        'user_id' => '1',
        'title' => 'Helpers in 15 Awesome 15 Awesome Laravel Collection Methods Collection Methods',
        'content' => 'Create custom helpers in 15 Awesome 15 Awesome Laravel Collection Methods Collection Methods',
        'category' => 'php'
    ],
    [
        'user_id' => '2',
        'title' => 'Testing in 15 Awesome 15 Awesome Laravel Collection Methods Collection Methods',
        'content' => 'Testing File Uploads in 15 Awesome 15 Awesome Laravel Collection Methods Collection Methods',
        'category' => 'php'
    ],
    [
        'user_id' => '3',
        'title' => 'Telegram Bot',
        'content' => 'Crypto Telegram Bot in 15 Awesome 15 Awesome Laravel Collection Methods Collection Methods',
        'category' => 'php'
    ],
]);
Copy after login

The above array is actually the value of the Post model. In this tutorial we will use this array for simplification. Remember, everything will be based on eloquent in the same way.

When we use helper methods on the eloquent collection, the database will not be queried again. We first want to get all the results from the database, then we use collection methods to filter and modify them without querying the database.

filter()

filter, one of the most useful laravel collection methods, allows you to filter the collection using callbacks. It only passes those items that return true. All other items are deleted. filter Returns a new instance without changing the original instance. It accepts value and key as two parameters in the callback.

$filter = $collection->filter(function($value, $key) {
    if ($value['user_id'] == 2) {
        return true;
    }
});

$filter->all();
Copy after login

all Method returns the underlying array. The above code returns the following response.

[
    1 => [
        "user_id" => 2,
        "title" => "Testing in 15 Awesome 15 Awesome Laravel Collection Methods Collection Methods",
        "content" => "Testing File Uploads in 15 Awesome 15 Awesome Laravel Collection Methods Collection Methods",
        "category" => "php"
    ]
]
Copy after login

search method can search a collection using a given value. If the value is in the collection, the corresponding key will be returned. If no data item matches the corresponding value, false will be returned.

$names = collect(['Alex', 'John', 'Jason', 'Martyn', 'Hanlin']);

$names->search('Jason');

// 2
Copy after login

search method uses loose comparison by default. You can pass true in its second parameter to use strict comparison.

You can also pass your own callback function to the search method. Will return the key of the first item that passes the callback's truth test.

$names = collect(['Alex', 'John', 'Jason', 'Martyn', 'Hanlin']);

$names->search(function($value, $key) {
    return strlen($value) == 6;
});

// 3
Copy after login

chunk()

chunk method splits a collection into multiple smaller collections of a given size. Very useful for displaying collections into a grid.

$prices = collect([18, 23, 65, 36, 97, 43, 81]);

$prices = $prices->chunk(3);

$prices->toArray();
Copy after login

The above code generates the effect.

[
    0 => [
        0 => 18,
        1 => 23,
        2 => 65
    ],
    1 => [
        3 => 36,
        4 => 97,
        5 => 43
    ],
    2 => [
        6 => 81
    ]
]
Copy after login

dump()

dump Method to print a collection. It can be used for debugging and finding content within a collection at any location.

$collection->whereIn('user_id', [1, 2])
    ->dump()
    ->where('user_id', 1);
Copy after login

dump The result of the above code.

15 Awesome 15 Awesome Laravel Collection Methods Collection Methods

map()

map method is used to traverse the entire collection. It accepts callback as parameter. value and key are passed to the callback. Callbacks can modify values ​​and return them. Finally, a new collection instance of the modified item is returned.

$changed = $collection->map(function ($value, $key) {
    $value['user_id'] += 1;
    return $value;
});

return $changed->all();
Copy after login

Basically, it increases user_id by 1.

The response to the above code is as follows.

[
    [
        "user_id" => 2,
        "title" => "Helpers in 15 Awesome 15 Awesome Laravel Collection Methods Collection Methods",
        "content" => "Create custom helpers in 15 Awesome 15 Awesome Laravel Collection Methods Collection Methods",
        "category" => "php"
    ],
    [
        "user_id" => 3,
        "title" => "Testing in 15 Awesome 15 Awesome Laravel Collection Methods Collection Methods",
        "content" => "Testing File Uploads in 15 Awesome 15 Awesome Laravel Collection Methods Collection Methods",
        "category" => "php"
    ],
    [
        "user_id" => 4,
        "title" => "Telegram Bot",
        "content" => "Crypto Telegram Bot in 15 Awesome 15 Awesome Laravel Collection Methods Collection Methods",
        "category" => "php"
    ]
];
Copy after login

zip()

The Zip method merges the values ​​of the given array with the values ​​of the collection. Values ​​with the same index are added together, which means that the first value of the array is merged with the first value of the collection. Here, I'll use the collection we just created above. This also works for Eloquent collections.

$zipped = $collection->zip([1, 2, 3]);

$zipped->all();
Copy after login

The JSON response will look like this.

15 Awesome 15 Awesome Laravel Collection Methods Collection Methods

So, basically that’s it. If the length of the array is less than the length of the collection, 15 Awesome 15 Awesome Laravel Collection Methods Collection Methods will add null to the end of the remaining elements of type Collection. Similarly, if the length of the array is greater than the length of the collection, 15 Awesome 15 Awesome Laravel Collection Methods Collection Methods will add null to elements of type Collection, followed by the array value.

whereNotIn()

You can use the whereNotIn method to simply filter a collection by key values ​​that are not contained in the given array. It's basically the opposite of whereIn. Additionally, this method uses relaxed comparison == when matching values.

Let's filter $collection where user_id is neither 1 nor 2.

$collection->whereNotIn('user_id', [1, 2]);
Copy after login

The above statement will only return the last item in $collection. The first parameter is the key and the second parameter is the value array. In the case of eloquent, the first parameter will be the name of the column and the second parameter will be an array of values.

max()

max 方法返回给定键的最大值。 你可以通过调用max来找到最大的 user_id。 它通常用于价格或任何其他数字之类的比较,但为了演示,我们使用 user_id。 它也可以用于字符串,在这种情况下,Z> a

$collection->max('user_id');
Copy after login

上面的语句将返回最大的 user_id,在我们的例子中是 3

pluck()

pluck 方法返回指定键的所有值。 它对于提取一列的值很有用。

$title = $collection->pluck('title');
$title->all();
Copy after login

结果看起来像这样。

[
  "Helpers in 15 Awesome 15 Awesome Laravel Collection Methods Collection Methods",
  "Testing in 15 Awesome 15 Awesome Laravel Collection Methods Collection Methods",
  "Telegram Bot"
]
Copy after login

使用 eloquent 时,可以将列名作为参数传递以提取值。 pluck 也接受第二个参数,对于 eloquent 的集合,它可以是另一个列名。 它将导致由第二个参数的值作为键的集合。

$title = $collection->pluck('user_id', 'title');
$title->all();
Copy after login

结果如下:

[
    "Helpers in 15 Awesome 15 Awesome Laravel Collection Methods Collection Methods" => 1,
    "Testing in 15 Awesome 15 Awesome Laravel Collection Methods Collection Methods" => 2,
    "Telegram Bot" => 3
]
Copy after login

each()

each 是一种迭代整个集合的简单方法。 它接受一个带有两个参数的回调:它正在迭代的项和键。 Key 是基于 0 的索引。

$collection->each(function ($item, $key) {
    info($item['user_id']);
});
Copy after login

上面代码,只是记录每个项的 user_id

在迭代 eloquent 集合时,您可以将所有列值作为项属性进行访问。 以下是我们如何迭代所有帖子。

$posts = App\Post::all();

$posts->each(function ($item, $key) {
    // Do something
});
Copy after login

如果回调中返回 false,它将停止迭代项目。

$collection->each(function ($item, $key) {
    // Tasks
    if ($key == 1) {
        return false;
    }
});
Copy after login

tap()

tap() 方法允许你随时加入集合。 它接受回调并传递并将集合传递给它。 您可以对项目执行任何操作,而无需更改集合本身。 因此,您可以在任何时候使用tap来加入集合,而不会改变集合。

$collection->whereNotIn('user_id', 3)
    ->tap(function ($collection) {
        $collection = $collection->where('user_id', 1);
        info($collection->values());
    })
    ->all();
Copy after login

在上面使用的 tap 方法中,我们修改了集合,然后记录了值。 您可以对 tap 中的集合做任何您想做的事情。 上面命令的响应是:

[
    [
        "user_id" => "1",
        "title" => "Helpers in 15 Awesome 15 Awesome Laravel Collection Methods Collection Methods",
        "content" => "Create custom helpers in 15 Awesome 15 Awesome Laravel Collection Methods Collection Methods",
        "category" => "php"
    ],
    [
        "user_id" => "2",
        "title" => "Testing in 15 Awesome 15 Awesome Laravel Collection Methods Collection Methods",
        "content" => "Testing File Uploads in 15 Awesome 15 Awesome Laravel Collection Methods Collection Methods",
        "category" => "php"
    ]
]
Copy after login

你可以看到 tap 不会修改集合实例。

pipe()

pipe 方法非常类似于 tap 方法,因为它们都在集合管道中使用。 pipe 方法将集合传递给回调并返回结果。

$collection->pipe(function($collection) {
    return $collection->min('user_id');
});
Copy after login

上述命令的响应是 1。 如果从 pipe回调中返回集合实例,也可以链接其他方法。

contains()

contains 方法只检查集合是否包含给定值。 只传递一个参数时才会出现这种情况。

$contains = collect(['country' => 'USA', 'state' => 'NY']);

$contains->contains('USA');
// true

$contains->contains('UK');
// false
Copy after login

如果将 键 / 值 对传递给 contains 方法,它将检查给定的键值对是否存在。

$collection->contains('user_id', '1');
// true

$collection->contains('title', 'Not Found Title');
// false
Copy after login

您还可以将回调作为参数传递给回调方法。 将对集合中的每个项目运行回调,如果其中任何一个项目通过了真值测试,它将返回 true 否则返回 false

$collection->contains(function ($value, $key) {
    return strlen($value[&#39;title&#39;]) < 13;
});
// true
Copy after login

回调函数接受当前迭代项和键的两个参数值。 这里我们只是检查标题的长度是否小于13。在 Telegram Bot 中它是12,所以它返回 true

forget()

forget 只是从集合中删除该项。 您只需传递一个键,它就会从集合中删除该项目。

$forget = collect([&#39;country&#39; => &#39;usa&#39;, &#39;state&#39; => &#39;ny&#39;]);

$forget->forget(&#39;country&#39;)->all();
Copy after login

上面代码响应如下:

[
    "state" => "ny"
]
Copy after login

forget 不适用于多维数组。

avg()

avg 方法返回平均值。 你只需传递一个键作为参数,avg 方法返回平均值。 你也可以使用 average 方法,它基本上是 avg 的别名。

$avg = collect([
    [&#39;shoes&#39; => 10],
    [&#39;shoes&#39; => 35],
    [&#39;shoes&#39; => 7],
    [&#39;shoes&#39; => 68],
])->avg(&#39;shoes&#39;);
Copy after login

上面的代码返回 30 ,这是所有四个数字的平均值。 如果你没有将任何键传递给avg 方法并且所有项都是数字,它将返回所有数字的平均值。 如果键未作为参数传递且集合包含键/值对,则 avg 方法返回 0。

$avg = collect([12, 32, 54, 92, 37]);

$avg->avg();
Copy after login

上面的代码返回 45.4,这是所有五个数字的平均值。

您可以使用这些 laravel 集合方法在您自己的项目中处理集合。

原文地址:https://tutsforweb.com/15-laravel-collection-methods/

译文地址:https://learnku.com/laravel/t/27647

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of 15 Awesome Laravel Collection Methods. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

See all articles