What is a Laravel Collection? A Beginner's Guide to Its Usage.
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
This article provides an overview of Laravel collections and explains how to use them for beginners.
The content is based on excerpts from the Laravel official documentation.
What is a Collection?
Simply put, it is similar to an array.
In Laravel, collections are used in the following cases:
- When retrieving data using
get()
orall()
. - When manually creating a collection using
collect
.
Why Use Collections?
By using collections, formatting arrays becomes more convenient.
For example, filtering and sorting data becomes much easier.
① Creating a Collection from a Simple Array
Without specifying keys, an array-like structure produces the following output:
$array = [1,2,3,4,5];
$collection1 = collect($array);
dd($collection1);
Illuminate\Support\Collection {#338 ▼
#items: array:5 [▼
0 => 1
1 => 2
2 => 3
3 => 4
4 => 5
]
}
You can retrieve elements by specifying their index.
dd($collection1[0]);
// Outputs: 1
② Creating a Collection with Keys
Unlike before, this example uses keys.
$array2 = [
[
'user_id'=> 1,
'name' => 'Sato',
],
[
'user_id'=> 2,
'name' => 'Takeru',
],
[
'user_id'=> 3,
'name' => 'Shun',
],
[
'user_id'=> 4,
'name' => 'Oguri',
],
];
$collection2 = collect($array2);
dd($collection2);
Output:
Illuminate\Support\Collection {#350 ▼
#items: array:4 [▼
0 => array:2 [▼
"user_id" => 1
"name" => "Sato"
]
1 => array:2 [▼
"user_id" => 2
"name" => "Takeru"
]
2 => array:2 [▼
"user_id" => 3
"name" => "Shun"
]
3 => array:2 [▼
"user_id" => 4
"name" => "Oguri"
]
]
}
Specifying an index like an array:
dd($collection2[0]);
Output:
// Retrieves only the first data entry.
array:2 [▼
"user_id" => 1
"name" => "Sato"
]
Retrieving a specific key:
dd($collection2[0]['user_id']);
Output:
// Retrieves only the user_id of the first entry.
1
Benefits
Using collections makes it easy to manipulate data, such as filtering and sorting.
Example
Let's retrieve the entry where user_id
is 1
.
// The 'where' method searches by key.
dd($collection2->where('user_id',1));
Output:
// Retrieved the entry with user_id = 1.
// If multiple entries have user_id = 1, all matching entries will be returned as a collection.
Illuminate\Support\Collection {#353 ▼
#items: array:1 [▼
0 => array:2 [▼
"user_id" => 1
"name" => "Sato"
]
]
}
Methods like where
and orderBy
are similar to those used in Eloquent for retrieving database records, making them easy to understand.
Points to Note
Keys are not automatically reset when filtering
When using Eloquent for filtering, keys are automatically assigned sequentially (from 0
onward) when retrieving records.
However, when formatting arrays using collections, the keys are not automatically reset. This may cause unexpected behavior in the frontend.
To reset keys after filtering, use the values()
method:
$items = $collection2->filter(function ($item) {
return $item['user_id'] === 1;
})->values(); // Use values() to reset keys
dd($newCollection);
Are Retrieved Database Records Always Collections?
A. Multiple records are retrieved as collections.
(Single records are retrieved as objects.)
For example:
Post::get();
Post::all();
These return collections, as they contain multiple records.
A. Single records are retrieved as objects.
Post::first();
Post::find(1);
These return objects, as they contain only one record.
Conclusion
Collections allow data to be formatted using function names similar to those in Eloquent.
When dealing with complex relational structures, some sorting or formatting may not be easily achievable with Eloquent alone.
In such cases, using collections can simplify data manipulation.
Sorting Data Based on Related Records in Laravel
Hope this article was helpful!