PHP code example of spatie / laravel-collection-macros

1. Go to this page and download the library: Download spatie/laravel-collection-macros library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

spatie / laravel-collection-macros example snippets


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

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

$currentItem = 3;

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

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

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

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

$data->second(); // 2

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

$data->third(); // 3

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

$data->fourth(); // 4

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

$data->fifth(); // 5

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

$data->sixth(); // 6

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

$data->seventh(); // 7

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

$data->eighth(); // 8

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

$data->ninth(); // 9

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

$data->tenth(); // 10

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

$data->getNth(11); // 11

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

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

$currentItem = 1;

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

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

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

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

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

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

$collection = collect(['a', 'b', 'c']);

$collection->containsAny(['b', 'c', 'd']); // returns true
$collection->containsAny(['c', 'd', 'e']); // returns true
$collection->containsAny(['d', 'e', 'f']); // returns false
$collection->containsAny([]); // returns false

$collection = collect(['a', 'b', 'c']);

$collection->containsAll(['b', 'c',]); // returns true
$collection->containsAll(['c', 'd']); // returns false
$collection->containsAll(['d', 'e']); // returns false
$collection->containsAll([]); // returns true

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

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

$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]

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

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

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

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

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

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

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

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

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

$collection = collect([
    'foo' => 'bar',
]);

$collection->getCaseInsensitive('Foo'); // returns 'bar';

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

$posts->groupByModel('category');

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

$collection = collect([
    'foo' => 'bar',
]);

$collection->hasCaseInsensitive('Foo'); // returns true;

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

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

$collection = collect([]);

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

if(mixed $if, mixed $then = null, mixed $else = null): mixed

collect()->if(true, then: true, else: false); // returns true
collect()->if(false, then: true, else: false); // returns false

// the `then` closure will be executed
// the first element of the returned collection now contains "THIS IS THE VALUE"
$collection = collect(['this is a value'])
    ->if(
        fn(Collection $collection) => $collection->contains('this is a value'),
        then: fn(Collection $collection) => $collection->map(fn(string $item) => strtoupper($item)),
        else: fn(Collection $collection) => $collection->map(fn(string $item) => Str::kebab($item))
    );

// the `else` closure will be executed
// the first element of the returned collection now contains "this-is-another-value"
$collection = collect(['this is another value'])
    ->if(
        fn(Collection $collection) => $collection->contains('this is a value'),
        then: fn(Collection $collection) => $collection->map(fn(string $item) => strtoupper($item)),
        else: fn(Collection $collection) => $collection->map(fn(string $item) => Str::kebab($item))
    );

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

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

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

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

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

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

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]

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

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

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

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

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

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

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

use Amp\Parallel\Worker\DefaultPool;

$pool = new DefaultPool(8);

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

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

$collection = new Collection([
    'foo' => [
        'bar' => [
            'baz' => 'value',
        ]
    ]
]);

$collection->path('foo.bar.baz') // 'value'

$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],
// ]);

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

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

// returns
// collect([
//     [1, 10],
//     [2, 20],
// ]);

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

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

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

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

collect([
  'item' => [
     'children' => []
  ]   
])->recursive();

// subsequent arrays are now collections

collect([
  'item' => [
     'children' => [
        'one' => [1],
        'two' => [2]
     ]
  ]   
])->recursive(1); // Collection(['item' => Collection(['children' => ['one' => [1], 'two' => [2]]])])

collect([
  'item' => [
     'children' => [
        'one' => [1],
        'two' => [2]
     ]
  ]   
])
  ->recursive(1)
  ->map(function ($item) {
    return $item->map(function ($children) {
      return $children->mapInto(Model::class);
    });
  }); // Collection(['item' => Collection(['children' => ['one' => Model(), 'two' => Model()]])])

// If we do not pass a max depth we will get the error "Argument #1 ($attributes) must be of type array"

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

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

$rotate->toArray();

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

$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'],
//     ]],
// ];

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

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

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

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

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

collect([
    ['Jane', 'Bob', 'Mary'],
    ['[email protected]', '[email protected]', '[email protected]'],
    ['Doctor', 'Plumber', 'Dentist'],
])->transpose()->toArray();

// [
//     ['Jane', '[email protected]', 'Doctor'],
//     ['Bob', '[email protected]', 'Plumber'],
//     ['Mary', '[email protected]', 'Dentist'],
// ]

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

$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']

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


collect(['[email protected]', 'bla'])->validate('email'); // returns false
collect(['[email protected]', '[email protected]'])->validate('email'); // returns true

// pass the field name that should be used as a weight

$randomItem = collect([
    ['value' => 'a', 'weight' => 30],
    ['value' => 'b', 'weight' => 20],
    ['value' => 'c', 'weight' => 10],
])->weightedRandom('weight');

$randomItem = collect([
    ['value' => 'a', 'weight' => 30],
    ['value' => 'b', 'weight' => 20],
    ['value' => 'c', 'weight' => 10],
])->weightedRandom(function(array $item) {
   return $item['weight'];
});

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