laravel collection values code example
Example 1: laravel collection group
$collection = collect([
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
['account_id' => 'account-x11', 'product' => 'Desk'],
]);
$grouped = $collection->groupBy('account_id');
$grouped->toArray();
/*
[
'account-x10' => [
['account_id' => 'account-x10', 'product' => 'Chair'],
['account_id' => 'account-x10', 'product' => 'Bookcase'],
],
'account-x11' => [
['account_id' => 'account-x11', 'product' => 'Desk'],
],
]
*/
Example 2: collection map laravel
// The array we're going to return
$data = [];
// Query the users table
$query = users::where('id', 1)->get();
// Let's Map the results from [$query]
$map = $query->map(
function($items){
$data['user_firstName'] = $items->firstName;
$data['user_lastName'] = $items->lastName;
return $data;
}
);
return $map;
Example 3: laravel collection methods
$collection = collect([1,2,3,4]);
$collection->each(function($item){
return $item*$item;
});
// [1,4,9,16]
Example 4: eloquent map collection
// The array we're going to return$data = [];// Query the users table$query = users::where('id', 1)->get();// Let's Map the results from [$query]$map = $query->map(function($items){ $data['user_firstName'] = $items->firstName; $data['user_lastName] = $items->lastName; return $data;});return $map;