• Время чтения ~7 мин
  • 08.04.2023

Laravel Eloquent использует коллекции для возврата результатов. Коллекции содержат очень полезные методы, что делает их очень мощными и полезными в использовании. Вы можете фильтровать их, модифицировать их и многое другое с ними очень удобно. Мы рассмотрим методы сбора laravel в этом уроке.

Коллекции не только ограничиваются красноречивыми результатами, но и могут использоваться отдельно. Красноречивые результаты используют коллекции. Можно просто создать коллекцию, передав массив collect вспомогательной функции. Все следующие методы сбора, перечисленные ниже, применимы как к красноречивым коллекциям, так и к самим коллекциям.

Допустим, у вас есть постмодель. Вы найдете все сообщения с php категорией.

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

The above command returns a collection. A collection is a laravel class that uses arrays internally and adds many features to them.

Вы можете создать коллекцию, просто используя collect такой метод.

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

Above array is actually the values of our Post model. In this tutorial, we will be using this array for simplification. Remember everything will work the same way for the eloquent as well.

Вот как вы можете просто создавать коллекции. Вы можете применить все вспомогательные методы сбора, доступные в Laravel.

Когда мы применяем вспомогательные методы к красноречивым коллекциям, они не запрашивают базу данных. Сначала берутся все результаты, которые мы хотим получить из базы данных, а затем мы используем методы коллекции для их фильтрации и изменения без каких-либо запросов к базе данных.

filter()

filter, один из самых полезных методов сбора laravel, позволяет фильтровать коллекцию с помощью обратного вызова. Он передает только те элементы, которые возвращают значение true. Все остальные элементы удаляются. filter возвращает новый экземпляр без изменения исходного экземпляра. Он принимает value и key в качестве двух параметров в обратном вызове.

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

$filter->all();

all method returns the underlying array. Above code returns the following response.

[
    1 => [
        "user_id" => 2,
        "title" => "Testing in Laravel",
        "content" => "Testing File Uploads in Laravel",
        "category" => "php"
    ]
]

search()

search method is used to search the collection for a given value. If the value is present in the collection, the key of the value is returned. If the value does not matches any item, false is returned.

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

$names->search('Jason');

// 2

By default, the search is done using loose comparison. You can pass true as the second argument to the search method to use strict comparison.

Можно также передать методу собственную функцию обратного search вызова. Он вернет ключ первого элемента, который проходит тест на истинность обратного вызова.

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

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

// 3

chunk()

chunk method is used to split the collection into multiple smaller collections of given size. It is useful displaying collections into the grid.

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

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

$prices->toArray();

Response from the above code.

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

dump()

dump method dumps the collection’s items. It is useful for debugging and finding what’s inside the collection at any point in the collection pipeline.

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

dump response from the above code.

laravel collection methods dump

map()

map method is used to iterate through the full collection. It accepts a callback as an argument. value and the key is passed to the callback. Callback can modify the values and return them. Finally, a new collection instance of modified items is returned.

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

return $changed->all();

Basically, it incremented user_id by one.

Ответ из приведенного выше кода выглядит следующим образом.

[
    [
        "user_id" => 2,
        "title" => "Helpers in Laravel",
        "content" => "Create custom helpers in Laravel",
        "category" => "php"
    ],
    [
        "user_id" => 3,
        "title" => "Testing in Laravel",
        "content" => "Testing File Uploads in Laravel",
        "category" => "php"
    ],
    [
        "user_id" => 4,
        "title" => "Telegram Bot",
        "content" => "Crypto Telegram Bot in Laravel",
        "category" => "php"
    ]
];

zip()

Метод Zip добавляет значения заданного массива со значениями коллекции. Значения добавляются к одному и тому же индексу, что означает, что первое значение массива будет объединено с первым значением коллекции. Здесь я использую массив коллекций, который мы создали выше. То же самое можно сказать и с красноречивыми коллекциями.

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

$zipped->all();

JSON Response looks like this.

laravel collection methods zip

Вот и все. Если количество массива меньше количества коллекций, laravel добавит null в конце оставшиеся элементы коллекции. Кроме того, если количество массива больше, чем количество коллекций, laravel добавит a null для элементов коллекции, за которым следует последующее значение массива.

whereNotIn()

Метод можно использовать whereNotIn для простой фильтрации коллекции по значению ключа, не содержащемуся в данном массиве. Это в основном противоположность whereIn. Кроме того, этот метод использует слабое сравнение == при сопоставлении значений.

Давайте отфильтруем $collection where user_id is ни to , ни 1 .

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

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

2 max()

max method returns the maximum value of a given key. You can find the maximum user_id by calling max. It’s normally used for things like price or any other number but for the sake of demonstration let’s use user_id. It can also be used with strings and in that case, Z > a.

$collection->max('user_id');

Above statement will return the maximum user_id which in our case is 3.

pluck()

pluck method returns all of the values for a key. It is useful for extracting values of one column.

$title = $collection->pluck('title');
$title->all();
The result looks like this.
[
  "Helpers in Laravel",
  "Testing in Laravel",
  "Telegram Bot"
]

When working with eloquent, you can pass a column name as an argument to extract its values. pluck also accepts a second argument and in the case of eloquent collections, it can be another column name. It will result in collection keyed by the values of the second argument.

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

The result looks like this:

[
    "Helpers in Laravel" => 1,
    "Testing in Laravel" => 2,
    "Telegram Bot" => 3
]

each()

each is a simple method for iterating over the full collection. It accepts a callback with two arguments: item it is iterating through and the key. Key is 0 based index.

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

Above, it is simply logging the user_id of each item.

При ведении журнала красноречивых коллекций можно получить доступ ко всем значениям столбцов в качестве свойств элемента. Вот как мы можем перебирать все сообщения.

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

$posts->each(function ($item, $key) {
    // Do something
});
If you return false from your callback, it will stop iterating over items.
$collection->each(function ($item, $key) {
    // Tasks
    if ($key == 1) {
        return false;
    }
});

tap()

tap() method allows you to tap into the collection at any point. It accepts a callback and passes and passes the collection to it. You can do anything with the items without changing the collection itself. So, you can use tap to peak into the collection at any point without mutating the collection.

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

In the tap method used above, we modified the collection and then logged the value. You can do anything you want with the collection inside the tap. Response from the above command is:

[
    [
        "user_id" => "1",
        "title" => "Helpers in Laravel",
        "content" => "Create custom helpers in Laravel",
        "category" => "php"
    ],
    [
        "user_id" => "2",
        "title" => "Testing in Laravel",
        "content" => "Testing File Uploads in Laravel",
        "category" => "php"
    ]
]

You can see that tap does not modify the collection instance. Learn more about tap helper function and tap collection method in detail.

pipe()

pipe method is very similar to the tap method in a sense that both of them are used inside the collection pipeline. pipe method passes the collection to the callback and return the result.

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

Response from the above command is 1. If you return an instance of collection from the pipe callback, you can chain further methods as well.

contains()

contains method simply checks if the collection contains a given value. It is only true when you pass a single argument.

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

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

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

If you pass a key / value pair to the contains method, it will check whether the given pair exists or not.

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

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

You can also pass a callback as an argument to the callback method. Callback will run for every item in the collection and if any of them passes the truth test, it will return true else false.

$collection->contains(function ($value, $key) {
    return strlen($value['title']) < 13;
});
// true

Callback accepts two arguments value of the currently iterating item and the key. Here we are simply checking if the length of the title is less than 13. In Telegram Bot it is 12, so it returned true.

forget()

forget simply removes the item from the collection. You simply pass a key and it will remove that item from the collection.

$forget = collect(['country' => 'usa', 'state' => 'ny']);

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

Response from the above code:

[
    "state" => "ny"
]

forget does not work on multi-dimensional arrays.

avg()

avg method returns the average value. You simply pass a key as an argument and the avg method returns the average. You can also use the average method which is basically an alias for avg.

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

Above code returns 30 which is the average of all four numbers. If you do not pass any key to avg method and all the items are numbers, it will return the avg of all numbers. If the key is not passed as an argument and the collection contains key / value pairs, avg method returns 0.

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

$avg->avg();

The above code returns 45.4 which is the average of all five numbers.

Вы можете использовать эти методы сбора laravel для работы со коллекцией в собственных проектах.

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

Про мене

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

Об авторе CrazyBoy49z
WORK EXPERIENCE
Контакты
Ukraine, Lutsk
+380979856297