Laravel

Collections & Arrays

Introduction

Arrays are basic lists of data, while Laravel Collections provide a powerful and expressive way to manipulate data with extensive methods for filtering, transforming, and more. They enhance code readability and performance, making data handling easier and more efficient in Laravel applications. For more information you can check collections

Arrays

In Laravel, Arrays are fundamental data structures used to store and organize collections of data. Arrays in Laravel are similar to standard PHP arrays but come with some additional functionalities and features that make them more versatile and powerful.

Basic Data Structure: Arrays are used to hold multiple values under a single variable. Each value in an array is associated with an index or key, which allows easy access and retrieval of specific elements.

Support for Mixed Data Types: Laravel arrays, like PHP arrays, can hold a mix of different data types, including integers, strings, floats, objects, and even other arrays.

Flexible Syntax: Arrays can be created using various syntaxes, such as numeric index-based arrays, associative arrays (key-value pairs), and multidimensional arrays (arrays within arrays).

Arrays in Laravel vs. PHP Arrays: Laravel's array functions and helpers are built on top of PHP's array functions, providing some additional conveniences and improvements.

Helper Functions: Laravel offers several helper functions to work with arrays more efficiently, such as array_add(), array_get(), array_pull(), and more.

Array Helper Class: Laravel provides the Illuminate\Support\Arr class, which offers additional array manipulation methods, including only(), except(), pluck(), etc.

Array Access: Laravel arrays can be accessed and manipulated using familiar PHP array access methods, such as square bracket notation ($array['key']) and array functions (array_key_exists(), count(), etc.).

Creating Arrays

  1. Associative Array (Key-Value Pairs):
$personDetails = [
    'name' => 'John Doe',
    'age' => 30,
    'email' => 'john@example.com',
];
  1. Multidimensional Array:
$students = [
    ['name' => 'John Doe', 'age' => 25, 'grade' => 'A'],
    ['name' => 'Jane Smith', 'age' => 23, 'grade' => 'B'],
    ['name' => 'Bob Johnson', 'age' => 22, 'grade' => 'C'],
];

Arrays Methods

  1. array_get(): Gets a value from an array using "dot" notation, providing a default value if the key does not exist.
  2. array_except(): Returns an array without the specified keys.
  3. array_first(): Returns the first element of an array that satisfies a given truth test.
  4. array_last(): Returns the last element of an array that satisfies a given truth test.
  5. array_only(): Returns an array with only the specified keys.
  6. array_pull(): Removes and returns a value from an array by its key.

example :-

$person = [
    'name' => 'John Doe',
    'age' => 30,
    'email' => 'john@example.com',
];

// Retrieve the value for the key 'name'
$name = array_get($person, 'name', 'Unknown');

// Output: 'John Doe'

// Trying to retrieve a non-existing key
$city = array_get($person, 'address.city', 'City Not Available');

// Output: 'City Not Available'
$data = [
    'name' => 'John Doe',
    'age' => 30,
    'email' => 'john@example.com',
    'city' => 'New York',
];

// Remove the 'age' and 'email' keys from the array
$filteredData = array_except($data, ['age', 'email']);

// Output: ['name' => 'John Doe', 'city' => 'New York']
$numbers = [2, 4, 6, 7, 8];

// Find the first even number
$firstEvenNumber = array_first($numbers, function ($value) {
    return $value % 2 === 0;
});

// Output: 2

Collections

Powerful Methods: Laravel Collections provide an extensive set of methods to manipulate, filter, transform, aggregate, and otherwise work with data. These methods are designed to simplify common data manipulation tasks and eliminate the need for repetitive loops or conditions.

Object-Oriented Abstraction: Collections are implemented as objects, which allows them to take advantage of object-oriented programming concepts. This makes the code more organized, reusable, and consistent.

Fluent Interface: Collections support a fluent interface, meaning you can chain multiple methods together, resulting in more concise and readable code.

Lazy Evaluation: Some methods in Collections use lazy evaluation, which means they do not execute the operation immediately. Instead, they return a new Collection instance with the operation queued up to be executed only when needed. This can improve performance, especially when working with large datasets.

Array-Like Access: While Collections are objects, they still allow you to access elements like an array using square brackets (e.g., $collection[0] ). This provides a familiar syntax for developers accustomed to working with arrays.

Creating Collections

To create a Collection, you can use the collect helper function or the Collection class's static make method

use Illuminate\Support\Collection;

// Sample array of data
$data = [
    ['name' => 'John', 'age' => 30],
    ['name' => 'Jane', 'age' => 25],
    ['name' => 'Alice', 'age' => 28],
];

// Create a Collection from the array
$collection = collect($data);

// Filter the collection to only contain people aged 28 and above
$filtered = $collection->where('age', '>=', 28);

// Output: Collection containing Alice and John

Collection Methods

  1. filter(): Filters the collection based on a given condition, returning a new collection with matching elements.
  2. map(): Transforms each element in the collection using a callback function, creating a new collection with the modified elements.
  3. pluck(): Extracts a specific value from each item in the collection, creating a new collection of those values.
  4. sortBy(): Sorts the collection based on a specified key or callback function.
  5. groupBy(): Groups the collection items by a specific key or callback function, returning a new collection with the groups as sub-collections.
  6. sum(): Calculates the sum of a specific key's values in the collection.
  7. count(): Returns the number of items in the collection.
  8. isEmpty(): Checks if the collection is empty.
  9. contains(): Checks if the collection contains a specific value.
  10. first(): Retrieves the first element of the collection.
  11. last(): Retrieves the last element of the collection.
  12. reduce(): Reduces the collection to a single value using a callback function.
  13. mapToGroups(): Transforms each item in the collection into a key-value pair, creating a new collection of groups.
  14. unique(): Removes duplicate values from the collection.

For more Collection function you can check Laravel collections Methods

example :-

use Illuminate\Support\Collection;

$books = [
    ['title' => 'Book 1', 'author' => 'Author A', 'price' => 20],
    ['title' => 'Book 2', 'author' => 'Author B', 'price' => 25],
    ['title' => 'Book 3', 'author' => 'Author A', 'price' => 18],
    ['title' => 'Book 4', 'author' => 'Author C', 'price' => 30],
    ['title' => 'Book 5', 'author' => 'Author B', 'price' => 22],
];

$collection = collect($books);

$filteredBooks = $collection->filter(function ($book) {
    return $book['price'] <= 25;
});

// Output: Collection containing Book 1, Book 3, Book 2, and Book 5
// Using map() to create a new collection with modified book titles
$modifiedTitles = $collection->map(function ($book) {
    return 'New Title: ' . $book['title'];
});

// Output: Collection containing the modified titles
// ['New Title: Book 1', 'New Title: Book 2', 'New Title: Book 3', 'New Title: Book 4', 'New Title: Book 5']
$bookTitles = $collection->pluck('title');

// Output: Collection containing 'Book 1', 'Book 2', 'Book 3', 'Book 4', and 'Book 5'
$groupedByAuthor = $collection->groupBy('author');

// Output: Collection with sub-collections for each author:
// ['Author A' => [...], 'Author B' => [...], 'Author C' => [...]]
$totalPrice = $collection->sum('price');

// Output: 115
$hasExpensiveBook = $collection->contains(function ($book) {
    return $book['price'] > 30;
});

// Output: false

Collections VS Arrays

The time taken for operations in Laravel Collections and Arrays can depend on the specific use case and the size of the data being processed. However, in general, Laravel Collections tend to be more efficient and performant than Arrays for various reasons

  • Method Chaining
  • Advanced Methods
  • Custom Collections

Let's consider a practical example to compare the usage of Laravel Collections and Arrays for data manipulation. In this example, we'll work with a dataset of Orders and Users common data operations using both Collections and Arrays.

Suppose we have a Order & user table in database.

Using Arrays

$orders = Order::all()->get();

$result = [];
foreach($orders as $order)
{
    echo "user ID: ".$order->user->id." = ".$order->user->name;

}

Using Collections

$orders = Order::all()->with(['user'])->get();

$orders = collect($orders);

foreach($orders as $order)
{
    echo $order->user->pluck('name');
}
  • In this Arrays example, you can see that for print user id and user name are on the base of order. Every time in foreach loop we create a connection with the database which takes time. Because of this code will take more time than collection in which we get all order and user data at one time.

Copyright © 2024