Collection::except

Returns all items apart from those stored under the given keys.

Signature
except(array|string|Enumerable $keys): Collection
  • Added in Laravel 5.0

Parameters

ParameterTypeDescription
$$keys\Illuminate\Support\Enumerable<array-key, TKey>|array<array-key, TKey>|stringKeys to remove. Accepts an array, a collection, or any number of string arguments. Passing null returns a copy of the whole collection.

Return value

Collection<TKey, TValue>A new collection containing every item whose key was not listed.

Changelog

  • PHP 5.xEloquent collections override except() to exclude models by primary key rather than by array key.

except() removes items by key and returns a new collection with everything else. It is the mirror of only(), and the collection form of Arr::except().

Keys, not values

The distinction from diff() matters: except() looks at keys and ignores values entirely, while diff() does the opposite. On a plain list, the keys are the numeric indexes, so collect(['a','b','c'])->except([1]) drops 'b' — the item at index 1, not the value 1. Keys of surviving items are preserved, leaving a sparse array that json_encode() renders as an object; call values() if a list is required.

Two calling styles

Both except(['a', 'b']) and except('a', 'b') work, because a non-array first argument makes the method collect all its arguments. A collection of keys works too.

Silent on missing keys

Listing a key that is not there is not an error and produces no warning. That makes it safe for sanitising input, but it also means a typo removes nothing and the field you meant to strip stays in the payload — worth an assertion in a test when the key holds a secret.

Nesting

Removal is top-level only. Dot notation does not reach into nested arrays; map over the items to strip a nested key.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Strip password and _token from request input before logging it.
  • Remove internal fields from a record before returning it in an API response.
  • Drop a handful of columns from a row without listing every column you want to keep.

Frequently asked questions

What is the difference between except() and diff() in Laravel collections?

except() removes items by key while diff() removes them by value. On a list, except([1]) drops the item at index 1, whereas diff([1]) looks for an item whose value is 1.

Does except() throw an error for a key that is not there?

No — missing keys are ignored silently and the collection comes back without them. That makes typos invisible, so assert on the result when you are stripping something sensitive.

Can except() remove a nested key with dot notation?

No, it only removes top-level keys. Map over the items and call except() on each nested structure, or use Arr::forget() with a dotted path on the underlying array.

More examples

except() removes by key, diff() removes by value

On a plain list the two methods answer different questions with the same-looking argument. except([1]) removed the second item because 1 is its key; diff([1]) looked for the value 1 and found none. Both leave the surviving keys untouched, so values() is needed before JSON encoding.

Example · php
<?php

$list = collect(['apple', 'banana', 'cherry']);

// Keys are the indexes 0, 1, 2 — this drops the item AT index 1.
print_r($list->except([1])->all());
// Array ( [0] => apple [2] => cherry )

// diff() looks at values, so this removes nothing.
print_r($list->diff([1])->all());
// Array ( [0] => apple [1] => banana [2] => cherry )

// Removing by value is diff()'s job.
print_r($list->diff(['banana'])->values()->all());
// Array ( [0] => apple [1] => cherry )

// except() leaves a gap; values() repacks it.
print_r($list->except([1])->values()->all());
// Array ( [0] => apple [1] => cherry )

Sanitising input and excluding models

The first block whitelists nothing and blacklists the sensitive fields, which is why the test asserting the key is gone matters — a misspelled key would leave the password in the log with no error. The final block shows the Eloquent override: the argument is a primary key, not an array index. Needs a booted application.

Example · php
<?php

// Strip secrets before logging.
$safe = collect($request->all())->except([
    'password', 'password_confirmation', '_token', 'card_number',
]);

Log::info('signup attempt', $safe->all());

// Guard against the silent-typo failure in a test.
test('signup log omits credentials', function () {
    $logged = collect(['email' => '[email protected]', 'password' => 'secret'])
        ->except(['password']);

    expect($logged->has('password'))->toBeFalse();
});

// Eloquent overrides except() to work on primary keys.
$users   = User::whereIn('id', [1, 2, 3])->get();
$others  = $users->except([2]);   // excludes the User with id 2

echo $others->pluck('id')->implode(','), PHP_EOL;
// 1,3

Discussion

  • Be the first to comment on this lesson.