What Are The Available Methods Of Collections In Laravel

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

The Illuminate\Support\Collection class provides a fluent, convenient wrapper for working with arrays of data.

What Are The Available Methods Of Collections In Laravel

Available Methods Of Collections In Laravel

For the remainder of this documentation, we'll discuss each method available on the Collection class. Remember, all of these methods may be chained to fluently manipulate the underlying array. Furthermore, almost every method returns a new Collection instance, allowing you to preserve the original copy of the collection when necessary:
 

 

all
average
avg
chunk
collapse
collect
combine
concat
contains
containsStrict
count
countBy
crossJoin
dd
diff
diffAssoc
diffKeys
dump
duplicates
duplicatesStrict
each
eachSpread
every
except
zip

filter
first
firstWhere
flatMap
flatten
flip
forget
forPage
get
groupBy
has
implode
intersect
intersectByKeys
isEmpty
isNotEmpty
join
keyBy
keys
last
macro
make
map
wrap

mapInto
mapSpread
mapToGroups
mapWithKeys
max
median
merge
mergeRecursive
min
mode
nth
only
pad
partition
pipe
pluck
pop
prepend
pull
push
put
random
reduce
reject
whereNull

 

replace
replaceRecursive
reverse
search
shift
shuffle
skip
skipUntil
skipWhile
slice
some
sort
sortBy
sortByDesc
sortDesc
sortKeys
sortKeysDesc
splice
split
sum
take
takeUntil
takeWhile
tap

times
toArray
toJson
transform
union
unique
uniqueStrict
unless
unlessEmpty
unlessNotEmpty
unwrap
values
when
whenEmpty
whenNotEmpty
where
whereStrict
whereBetween
whereIn
whereInStrict
whereInstanceOf
whereNotBetween
whereNotIn
whereNotInStrict
whereNotNull

 

We see some examples for Available Methods of Collections

Example(1)

all()
The all method returns the underlying array represented by the collection:

collect([1, 2, 3])->all();

// [1, 2, 3]


Example(2)
 

contains($key, $operator = null, $value = null)

The contains method may be used to determine if a given model instance is contained by the collection. This method accepts a primary key or a model instance:

$users->contains(1);

$users->contains(User::find(1));


Example(3)
unique($key = null, $strict = false)

The unique method returns all of the unique models in the collection. Any models of the same type with the same primary key as another model in the collection are removed.

$users = $users->unique();


Example(4)
diff($items)
  The diff method returns all of the models that are not present in the given collection:

use App\User;

$users = $users->diff(User::whereIn('id', [1, 2, 3])->get());


Example(5)
 
except($keys)
The except method returns all of the models that do not have the given primary keys:

$users = $users->except([1, 2, 3]);

Related Post