create a collection in laravel in php

To create a collection in Laravel, you can use the collect() helper function provided by Laravel's Eloquent ORM.

main.php
use Illuminate\Support\Collection;

$users = collect([
    ['name' => 'John', 'email' => 'john@example.com'],
    ['name' => 'Jane', 'email' => 'jane@example.com'],
    ['name' => 'Bob', 'email' => 'bob@example.com'],
]);

// You can also create an empty collection using the `collect()` helper function without any arguments
$emptyCollection = collect();
356 chars
11 lines

Adding items to a collection is easy using the push() method.

main.php
$users->push(['name' => 'Alice', 'email' => 'alice@example.com']);

// You can also use `put()` to add new items or update existing items
$users->put(3, ['name' => 'Kate', 'email' => 'kate@example.com']);
205 chars
5 lines

The collection also provides many helpful methods to work with the data in the collection such as filter(), map(), pluck(), toArray(), and toJson() and much more.

main.php
// Filter the users collection by email address
$filteredUsers = $users->filter(function ($user) {
    return strpos($user['email'], 'example.com') !== false;
});

// Get a collection of user names
$userNames = $users->pluck('name');

// Convert the collection to an array or JSON
$userArray = $users->toArray();
$userJson = $users->toJson();
343 chars
12 lines

These are just a few examples of what you can do with collections in Laravel. The Laravel documentation has a comprehensive list of available collection methods that you can use to manipulate and transform your data.

gistlibby LogSnag