search
HomePHP FrameworkLaravelSummarize 15 commonly used Laravel collections (Collection)

The following is the Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection) tutorial column to introduce you to fifteen commonly used Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection) collections (Collections), I hope it will be helpful to friends in need!

Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)
Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection) 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.
Collections are 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.

Let’s say you have a Post model. You found all posts in the php category.

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

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 Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)',
        'content' => 'Create custom helpers in Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)',
        'category' => 'php'
    ],
    [
        'user_id' => '2',
        'title' => 'Testing in Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)',
        'content' => 'Testing File Uploads in Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)',
        'category' => 'php'
    ],
    [
        'user_id' => '3',
        'title' => 'Telegram Bot',
        'content' => 'Crypto Telegram Bot in Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)',
        'category' => 'php'
    ],
]);

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();

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

[
    1 => [
        "user_id" => 2,
        "title" => "Testing in Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)",
        "content" => "Testing File Uploads in Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)",
        "category" => "php"
    ]
]

search()

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

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

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();

The above code generates the effect.

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

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);

dump The result of the above code.

Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)

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();

Basically, it increases user_id by 1.

The response to the above code is as follows.

[
    [
        "user_id" => 2,
        "title" => "Helpers in Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)",
        "content" => "Create custom helpers in Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)",
        "category" => "php"
    ],
    [
        "user_id" => 3,
        "title" => "Testing in Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)",
        "content" => "Testing File Uploads in Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)",
        "category" => "php"
    ],
    [
        "user_id" => 4,
        "title" => "Telegram Bot",
        "content" => "Crypto Telegram Bot in Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)",
        "category" => "php"
    ]
];

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();

The JSON response will look like this.

Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)

So, basically that’s it. If the length of the array is less than the length of the collection, Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection) 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, Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection) 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.

让我们过滤 $collection,其中 user_id 既不是 1 也不是 2的。

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

上面的语句将只返回 $collection 中的最后一项。 第一个参数是键,第二个参数是值数组。 如果是 eloquent 的话,第一个参数将是列的名称,第二个参数将是一个值数组。

max()

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

$collection->max('user_id');

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

pluck()

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

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

结果看起来像这样。

[
  "Helpers in Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)",
  "Testing in Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)",
  "Telegram Bot"
]

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

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

结果如下:

[
    "Helpers in Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)" => 1,
    "Testing in Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)" => 2,
    "Telegram Bot" => 3
]

each()

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

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

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

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

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

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

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

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

tap()

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

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

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

[
    [
        "user_id" => "1",
        "title" => "Helpers in Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)",
        "content" => "Create custom helpers in Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)",
        "category" => "php"
    ],
    [
        "user_id" => "2",
        "title" => "Testing in Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)",
        "content" => "Testing File Uploads in Summarize 15 commonly used Summarize 15 commonly used Summarize 15 commonly used Laravel collections (Collection) collections (Collection) collections (Collection)",
        "category" => "php"
    ]
]

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

pipe()

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

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

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

contains()

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

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

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

$contains->contains('UK');
// false

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

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

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

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

$collection->contains(function ($value, $key) {
    return strlen($value['title']) <p>回调函数接受当前迭代项和键的两个参数值。 这里我们只是检查标题的长度是否小于13。在 <code>Telegram Bot</code> 中它是12,所以它返回 <code>true</code>。</p><p><strong>forget()</strong></p><p><code>forget</code> 只是从集合中删除该项。 您只需传递一个键,它就会从集合中删除该项目。</p><pre class="brush:php;toolbar:false">$forget = collect(['country' => 'usa', 'state' => 'ny']);

$forget->forget('country')->all();

上面代码响应如下:

[
    "state" => "ny"
]

forget 不适用于多维数组。

avg()

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

$avg = collect([
    ['shoes' => 10],
    ['shoes' => 35],
    ['shoes' => 7],
    ['shoes' => 68],
])->avg('shoes');

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

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

$avg->avg();

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

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

The above is the detailed content of Summarize 15 commonly used Laravel collections (Collection). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
laravel单点登录方法详解laravel单点登录方法详解Jun 15, 2022 am 11:45 AM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于单点登录的相关问题,单点登录是指在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统,下面一起来看一下,希望对大家有帮助。

一起来聊聊Laravel的生命周期一起来聊聊Laravel的生命周期Apr 25, 2022 pm 12:04 PM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于Laravel的生命周期相关问题,Laravel 的生命周期从public\index.php开始,从public\index.php结束,希望对大家有帮助。

laravel中guard是什么laravel中guard是什么Jun 02, 2022 pm 05:54 PM

在laravel中,guard是一个用于用户认证的插件;guard的作用就是处理认证判断每一个请求,从数据库中读取数据和用户输入的对比,调用是否登录过或者允许通过的,并且Guard能非常灵活的构建一套自己的认证体系。

laravel中asset()方法怎么用laravel中asset()方法怎么用Jun 02, 2022 pm 04:55 PM

laravel中asset()方法的用法:1、用于引入静态文件,语法为“src="{{asset(‘需要引入的文件路径’)}}"”;2、用于给当前请求的scheme前端资源生成一个url,语法为“$url = asset('前端资源')”。

实例详解laravel使用中间件记录用户请求日志实例详解laravel使用中间件记录用户请求日志Apr 26, 2022 am 11:53 AM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于使用中间件记录用户请求日志的相关问题,包括了创建中间件、注册中间件、记录用户访问等等内容,下面一起来看一下,希望对大家有帮助。

laravel中间件基础详解laravel中间件基础详解May 18, 2022 am 11:46 AM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于中间件的相关问题,包括了什么是中间件、自定义中间件等等,中间件为过滤进入应用的 HTTP 请求提供了一套便利的机制,下面一起来看一下,希望对大家有帮助。

laravel的fill方法怎么用laravel的fill方法怎么用Jun 06, 2022 pm 03:33 PM

在laravel中,fill方法是一个给Eloquent实例赋值属性的方法,该方法可以理解为用于过滤前端传输过来的与模型中对应的多余字段;当调用该方法时,会先去检测当前Model的状态,根据fillable数组的设置,Model会处于不同的状态。

laravel路由文件在哪个目录里laravel路由文件在哪个目录里Apr 28, 2022 pm 01:07 PM

laravel路由文件在“routes”目录里。Laravel中所有的路由文件定义在routes目录下,它里面的内容会自动被框架加载;该目录下默认有四个路由文件用于给不同的入口使用:web.php、api.php、console.php等。

See all articles

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)