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 |
filter |
mapInto
|
replace |
times |
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]
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));
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();
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());
except($keys)
The except method returns all of the models that do not have the given primary keys:
$users = $users->except([1, 2, 3]);