https://dev.to/ashallendesign #introduction Introduction https://collect.js.org is a JavaScript library by https://twitter.com/ecrmnn that provides a convenient layer over the top of arrays. It offers a near-identical API to https://laravel.com/docs/9.x/collections and makes working with arrays much easier (at least, in my opinion).

Example: const collection = collect([1, 2, 3, 4]); const filtered = collection.filter((value, key) => value > 2); // 'filtered' will now only include: // [3, 4] #reject reject

Let's imagine that we want to use the where method in a Laravel Collection: $users = [['name' => 'Ash', 'is_verified' => false], ['name' => 'Daniel', 'is_verified' => true], ['name' => 'Taylor', 'is_verified' => 'true'], ['name' => 'Jeffrey', 'is_verified' => 1], ]; $filtered = collect($items)->where('is_verified', true); // $filtered would now contain the following items: // ['name' => 'Daniel', 'is_verified' => true] // ['name' => 'Taylor', 'is_verified' => 'true'] // ['name' => 'Jeffrey', 'is_verified' => 1]

If we wanted to perform a strict comparison (similar to the Collection's whereStrict method), then we could use the where method like so: const items = [{name: 'Ash', is_verified: false}, {name: 'Daniel', is_verified: true}, {name: 'Taylor', is_verified: 'true'}, {name: 'Jeffrey', is_verified: 1}, ]; const filtered = collect(items).where('is_verified', '===', true); // 'filtered' would now contain the following items: // {name: 'Daniel', is_verified: true}
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Community Partners