Those useful collection methods in Laravel

Preface

Collection is a very useful data type. In PHP, we often use arrays to process data, and laravel provides many ways to process data encapsulated by collections. Many arrays can’t do or deal with cumbersome things, but collections can easily Doing so will save us a few ways to process data.

Instructions:

  1. collect() creates a collection. The
    helper function collect returns a new Illuminate\Support\Collection instance for a given array
$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'
    ]
]);
  1. search() Find the set of the 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']);

$result = $names->search('Jason');

// 2
  1. chunk() The
    chunk method divides the collection into multiple smaller collections of a given size. Very useful to display the collection in a grid
在这里插入代码片

4.where() query
where method, like database query method where() can filter the collection by given key-value pair:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
]);
$result = $collection->where('price', 100)->all();

/*
[
    1 =>['product' => 'Chair', 'price' => 100],
    3 =>['product' => 'Door', 'price' => 100],
]
*/
  1. dump() Print the collection
    dump method of printing the collection. It can be used to debug at any location and find the content in the collection
$collection->whereIn('price', [100, 150])
    ->dump()
    ->where('product', 'Door');
  1. map() traverse the collection

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

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

$result = $changed->all();

  1. max() maximum
$result = $collection->max('price');

//200
  1. pluck() Get the value of a column
$result = $collection->pluck('product')->all();

//["Desk","Chair","Bookcase","Door"];
  1. contains() The
    contains method only checks whether the collection contains the given value. This happens when only one parameter is passed
$contains = collect(['country' => 'USA', 'state' => 'NY']);

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

$contains->contains('UK');
// false
  1. forget()
    forget removes the item from the collection. Pass a key and it will remove the item from the collection.
$forget = collect(['country' => 'usa', 'state' => 'ny']);

$forget->forget('country')->all();
/*
[
    "state" => "ny"
]
*/
  1. zip() The
    zip method merges the values ​​of a given array at the index corresponding to the value of the collection:
$collection = collect(['Chair', 'Desk']);

$result = $collection->zip([100, 200])->all();

// [['Chair', 100], ['Desk', 200]]
  1. combine() The
    combine method can concatenate the keys of a collection with the values ​​of another array or collection:
$collection = collect(['name', 'age']);

$combined = $collection->combine(['George', 29]);

$combined->all();
// ['name' => 'George', 'age' => 29]
  1. diff() The
    diff method compares a collection with another collection or native PHP array in a value-based manner. This method will return values ​​that exist in the original collection but not in the given collection.
$collection = collect([1, 2, 3, 4, 5]);
$diff = $collection->diff([2, 4, 6, 8]);
$diff->all();
// [1, 3, 5]
  1. diffAssoc()

The diffAssoc method compares a collection with another collection or a native PHP array based on the key value. This method returns key-value pairs that only exist in the first collection:

$collection = collect([
    'color' => 'orange',
    'type' => 'fruit',
    'remain' => 6
]);

$diff = $collection->diffAssoc([
    'color' => 'yellow',
    'type' => 'fruit',
    'remain' => 3,
    'used' => 6
]);

$result = $diff->all();

// ['color' => 'orange', 'remain' => 6]
  1. first(), last() The
    first method returns the first element of the collection:

$result = collect([1, 2, 3, 4])->first();
// 1

$result = collect([1, 2, 3, 4])->first(function ($value, $key) {
    
    
    return $value > 2;
});
// 3

$result = collect([1, 2, 3, 4])->last();
// 4
  1. flatten()

The flatten method turns a multi-dimensional collection into one-dimensional:

$collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]);

$flattened = $collection->flatten();

$flattened->all();

// ['taylor', 'php', 'javascript'];
  1. flip() The
    flip method swaps the key values ​​of the collection:
$collection = collect(['name' => 'taylor', 'framework' => 'laravel']);

$flipped = $collection->flip();

$flipped->all();

// ['taylor' => 'name', 'laravel' => 'framework']
  1. forPage() The
    forPage method returns a new collection containing data items for a given number of pages. This method receives the number of pages as the first parameter, and the number of data items displayed on each page as the second parameter
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);

$chunk = $collection->forPage(2, 3);

$chunk->all();

// [4, 5, 6]
  1. groupBy()

The groupBy method groups collection data items by a given key

$collection = collect([
    ['account_id' => 'account-x10', 'product' => 'Chair'],
    ['account_id' => 'account-x10', 'product' => 'Bookcase'],
    ['account_id' => 'account-x11', 'product' => 'Desk'],
]);

$grouped = $collection->groupBy('account_id');

$grouped->toArray();

/*
[
    'account-x10' => [
        ['account_id' => 'account-x10', 'product' => 'Chair'],
        ['account_id' => 'account-x10', 'product' => 'Bookcase'],
    ],
    'account-x11' => [
        ['account_id' => 'account-x11', 'product' => 'Desk'],
    ],
]
*/
  1. keyBy() The
    keyBy method takes the value of the specified key as the key of the collection. If multiple data items have the same key, only the last one will appear in the new collection
$collection = collect([
    ['product_id' => 'prod-100', 'name' => 'desk'],
    ['product_id' => 'prod-200', 'name' => 'chair'],
]);

$keyed = $collection->keyBy('product_id');

$keyed->all();

/*
[
    'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
    'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
]
*/
  1. sort(), sortBy(), sortByDesc() sort

The sort method sorts the collection. The sorted collection retains the original array key. The
sortBy() method sorts the collection by the given key (ascending order). The sorted collection retains the original array index. In this example, the values ​​method is used The reset key is a continuous index.
sortByDesc() is in descending order

$collection = collect([5, 3, 1, 2, 4]);
$sorted = $collection->sort();
$sorted->values()->all();
// [1, 2, 3, 4, 5]
$collection = collect([
    ['name' => 'Desk', 'price' => 200],
    ['name' => 'Chair', 'price' => 100],
    ['name' => 'Bookcase', 'price' => 150],
]);

$sorted = $collection->sortBy('price');

$sorted->values()->all();

/*
[
    ['name' => 'Chair', 'price' => 100],
    ['name' => 'Bookcase', 'price' => 150],
    ['name' => 'Desk', 'price' => 200],
]
*/

You can use callbacks to determine how to sort the values ​​of the collection:

$collection = collect([
    ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
    ['name' => 'Chair', 'colors' => ['Black']],
    ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
]);

$sorted = $collection->sortBy(function ($product, $key) {
    
    
    return count($product['colors']);
});

$sorted->values()->all();

/*
    [
        ['name' => 'Chair', 'colors' => ['Black']],
        ['name' => 'Desk', 'colors' => ['Black', 'Mahogany']],
        ['name' => 'Bookcase', 'colors' => ['Red', 'Beige', 'Brown']],
    ]
*/
  1. take()

The take method uses a specified number of data items to return a new collection:

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

$chunk = $collection->take(3);

$chunk->all();

// [0, 1, 2]

Chinese documentation of laravel collection usage: https://laravelacademy.org/post/19507

Guess you like

Origin blog.csdn.net/qq_39004843/article/details/112799816