laravel collection to array code example
Example 1: laravel eloquent to array key value
Icon::all()->keyBy('name')
Example 2: collection map laravel
$data = [];
$query = users::where('id', 1)->get();
$map = $query->map(
function($items){
$data['user_firstName'] = $items->firstName;
$data['user_lastName'] = $items->lastName;
return $data;
}
);
return $map;
Example 3: pluck laravel
$name = DB::table('users')->where('name', 'John')->pluck('name');
Example 4: laravel eloquent to array key value
$roles = collect(DB::table('roles')->get())->keyBy('name');
Example 5: laravel collection methods
$collection = collect([1,2,3,4]);
$collection->each(function($item){
return $item*$item;
});
Example 6: get item from collection that match
$artist = 'Vincent John Doe';
$art_collection = $paintings->filter(function ($painting) use ($artist) {
return $painting->artist == $artist;
});
foreach($paintings as $painting) {
if($painting->artist == $artist) {
$art_collection[] = $painting;
}
}