These are simple array and object collections that provide convinient methods to manipulate them.

Overview

Simple Collections

Minimum PHP Version License Total Downloads

These are simple array and object collections that provide convinient methods to manipulate collections;

To install this package type composer require temkaa/simple-collections in your project root directory.

Quickstart

<?php declare(strict_types = 1);

use SimpleCollections\Collections\Collection;

class SomeClass
{
    public function someArrayFunction(): void
    {
        $array = [
            ['product_id' => 2, 'product_name' => 'milk'],
            ['product_id' => 6, 'product_name' => 'bread'],
            ['product_id' => 1, 'product_name' => 'meat'],
            ['product_id' => 2, 'product_name' => 'juice'],
        ];

        var_dump(
            Collection::init($array)->sortBy('id', 'desc')->all(),
            Collection::init($array)->whereIn('product_id', [1, 2, 3])->all()
        );
    }

    public function someObjectFunction(): void
    {
        $result = Database::all() // Some database query
        
        var_dump(
            Collection::init($result, staticProps: false)->sortBy('id', 'desc')->all(),
            Collection::init($result, staticProps: false)->whereIn('product_id', [1, 2, 3])->all()
        );
    }
}

Object collection types

Please note, that if you want to make an object collection with static properties then init collection with Collection::init($arrayOfObjects)
If you want to make an object collection with dynamic properties that doesn't exist or are accessed via __get method then init collection with Collection::init($arrayOfObjects, staticProps: false)

Functionality

static init(array $array): ArrayCollection|ObjectCollection

This method returns an instance of collection. If the provided array has incorrect format, then InvalidInputFormatException will be thrown.
Collection::init([['id' => 1]])

where(string $fieldName, mixed $fieldValue): Collection

Using this method you can retrieve array elements with specified value.
$collection->where('id', 2)

where(string $fieldName, string $operator, mixed $value): Collection

Using this method you can retrieve array elements with operator rule.
If you will pass incorrent operator, the InvalidOperatorException will ge thrown.
Example: $collection->where('id', '<', 5)
Allowed operators:

  • ==
  • <>
  • <
  • >
  • <=
  • >=
  • ===
  • !==

where(array $options): Collection

Using this method you can specify array of rules, like in first two examples given. This is equivalent to calling the previous method.

$collection->where([
    ['id', '>', 10],
    ['value', '===', 15]
])

whereIn(string $fieldName, array $values): Collection

Using this method you can get array of elements, which specified field value is in given array.
$collection->whereIn('id', [1, 2, 3])

whereNotIn(string $fieldName, array $values): Collection

Using this method you can get array of elements, which specified field value is not exist in given array.
$collection->whereNotIn('id', [1, 2, 3])

map(callable $function): array

Using this function you can map through the array and cast the fiven function to all elements.
$collection->map(fn ($element) => $element['id'])

reject(callable $function): Collection

Using this method you can delete items by any rule. In given example collection will delete all elements, which id parameter equals to 2
$collection->reject(fn ($element) => $element['id'] === 2)

sort(string $field, string $sortMethod = 'asc'): Collection

Using this method you can sort the array.
$collection->sort('id', 'desc')

filter(callable $fn): Collection

Using this method you can filter collection using callback.
$collection->filter(fn ($element) => $element['a'] + $element['b'] > 10)

isEmpty(): bool

Using this method you will know if the collection is empty.
$collection->isEmpty()

isNotEmpty(): bool

This function is opposite to function isEmpty.
$collection->isNotEmpty()

count(): int

This method will return count of items in collection.
$collection->count()

first(): null|array|object

This method will return first collection item (return type depends on if collection is object or array). If the collection is empty, null will be returned.
$collection->first()

last(): null|array|object

This method will return last collection item (return type depends on if collection is object or array). If the collection is empty, null will be returned.
$collection->last()

all(): array

This method will return the result array.
$collection->all()

You might also like...
View themes is a simple package to provide themed view support to Laravel.

Laravel View Themes View themes is a simple package to provide themed view support to Laravel. Installation Add alexwhitman/view-themes to the require

This project uses dflydev/dot-access-data to provide simple output filtering for cli applications.

FilterViaDotAccessData This project uses dflydev/dot-access-data to provide simple output filtering for applications built with annotated-command / Ro

An opinionated support package for Laravel, that provides flexible and reusable helper methods and traits for commonly used functionality.

Support An opinionated support package for Laravel, that provides flexible and reusable helper methods and traits for commonly used functionality. Ins

A light weight laravel package that facilitates dealing with arabic concepts using a set of classes and methods to make laravel speaks arabic

A light weight laravel package that facilitates dealing with arabic concepts using a set of classes and methods to make laravel speaks arabic! concepts like , Hijri Dates & Arabic strings and so on ..

This package provides convenient methods for making token code, sending and verifying mobile phone verification requests.
This package provides convenient methods for making token code, sending and verifying mobile phone verification requests.

Laravel Mobile Verification Introduction Many web applications require users to verify their mobile phone numbers before using the application. Rather

Stop duplicating your Eloquent query scopes and constraints in PHP. This package lets you re-use your query scopes and constraints by adding them as a subquery.

Laravel Eloquent Scope as Select Stop duplicating your Eloquent query scopes and constraints in PHP. This package lets you re-use your query scopes an

Quickly identify controller methods with no route in your Laravel applications.
Quickly identify controller methods with no route in your Laravel applications.

Orphan Controller Quickly identify controller methods with no route in your Laravel applications. Installation You can install the package via Compose

Control frontend access to properties/methods in Livewire using PHP 8 attributes.
Control frontend access to properties/methods in Livewire using PHP 8 attributes.

This package adds PHP 8.0 attribute support to Livewire. In specific, the attributes are used for flagging component properties and methods as frontend-accessible.

A Laravel response helper methods.
A Laravel response helper methods.

A Laravel response helper methods. The package respond provides a fluent syntax to form array or json responses.

Releases(3.2.0)
Owner
Artem
Backend PHP programmer.
Artem
Source code behind the Laracasts Larabit: My Favorite Laravel Collections Methods

My Favorite Laravel Collections Methods This is the source code behind the Laracasts Larabit: My Favorite Laravel Collections Methods, and features al

Andrew Schmelyun 2 Dec 2, 2021
webtrees module: enhanced clippings cart with more functions to add records to the clippings cart and to start actions on these records

webtrees module hh_clippings_cart_enhanced !!! This is an alpha version! Do not use it in a productive webtrees system! !!! This webtrees custom modul

Hermann Hartenthaler 1 Sep 18, 2022
These projects are free for public use. Be a lesson for those who violate the rights of others!! ✌️

Faraz Kish Projects These projects are free for public use. Be a lesson for those who violate the rights of others!! ✌️ Brands Farazkish Uinvest MFina

Milad Shahi 30 May 20, 2022
Load files and classes as lazy collections in Laravel.

Lody Load files and classes as lazy collections in Laravel. Installation composer require lorisleiva/lody Usage Lody enables you to fetch all exist

Loris Leiva 64 Dec 22, 2022
A Collections-only split from Laravel's Illuminate Support

Collect - Illuminate Collections Deprecated: With the separation of Illuminate's Collections package, Collect is no longer necessary ?? . We will main

Tighten 1.5k Dec 28, 2022
A Collections-only split from Laravel's Illuminate Support

Collect - Illuminate Collections Deprecated: With the separation of Illuminate's Collections package, Collect is no longer necessary ?? . We will main

Tighten 1.5k Dec 30, 2022
Get estimated read time of an article. Similar to medium.com's "x min read". Multilingual including right-to-left written languages. Supports JSON, Array and String output.

Read Time Calculates the read time of an article. Output string e.g: x min read or 5 minutes read. Features Multilingual translations support. Static

Waqar Ahmed 8 Dec 9, 2022
Laravel Livewire (TALL-stack) form generator with realtime validation, file uploads, array fields, blade form input components and more.

TALL-stack form generator Laravel Livewire, Tailwind forms with auto-generated views. Support Contributions Features This is not an admin panel genera

TinaH 622 Jan 2, 2023
Improved Laravel dot notation for explicit array keys.

Laravel Explicit Array Improved Laravel dot notation for explicit array keys. ?? Supporting If you are using one or more Renoki Co. open-source packag

Renoki Co. 7 Nov 28, 2022
An abstraction layer to get data from array or a file with dot-notation

Alex Unruh - Config This library is based on the Laravel config concept. It values performance and was built on top of the library Dflydev Dot Access

Alexandre Odair 3 May 20, 2022