Skip to content

Instantly share code, notes, and snippets.

@fhdalikhan
Last active December 17, 2020 23:02
Show Gist options
  • Save fhdalikhan/d7dacb97ac1be5ed8aa192c563d49dcc to your computer and use it in GitHub Desktop.
Save fhdalikhan/d7dacb97ac1be5ed8aa192c563d49dcc to your computer and use it in GitHub Desktop.
Notes related to Laravel collections
<?php
# 1
$rows = collect(['Administration', 'Samples', 'Test 1', 'Test 2',]);
# running filter on the collection, if true is returned from the callback then the element will remain the in collection.
$rows = $rows->filter(function($item){
// dump($item);
# creating a collection, then checking with contains($item['name']) if the collection contains the item, using a ! at the start to not include the items which are in the checked collection.
return !collect(['Administration', 'Samples',])->contains($item['name']);
});
dd($rows);
# 2
# use map to add a new field to the collection
$rows = User::select(['id', 'title', 'created_at'])->get()->map(function($user){
$user->registered = $user->created_at->diffForHumans();
return $user;
});
dd($rows);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment