only() and except()

Whitelist or blacklist keys from an array.

Syntax\Illuminate\Support\Arr::only($array, ['a', 'b']);

The Arr::only() method keeps just the specified keys, while Arr::except() removes them. These are great for cleaning up request data before saving it.

Example

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

When to use it

  • A form handler uses Arr::only() to whitelist the permitted POST fields from the raw request input before passing them to the model's create() method.
  • An API adapter strips an external vendor response down to the three fields the system actually needs, ignoring the rest with Arr::only().
  • A serialiser uses Arr::except() to remove internal fields like 'password' and 'remember_token' before converting a user record to JSON.

More examples

Keep only allowed fields

Arr::only() returns a new array containing only the specified keys, dropping everything else including sensitive fields.

Example · php
use Illuminate\Support\Arr;

$request = [
    'name'     => 'Alice',
    'email'    => '[email protected]',
    'password' => 'secret',
    '_token'   => 'abc123',
];

$safe = Arr::only($request, ['name', 'email']);
// => ['name' => 'Alice', 'email' => '[email protected]']

Exclude sensitive keys with Arr::except()

Arr::except() is the inverse of Arr::only(), removing the listed keys and returning everything else.

Example · php
use Illuminate\Support\Arr;

$user = [
    'id'             => 42,
    'name'           => 'Bob',
    'email'          => '[email protected]',
    'password'       => '$2y$10$...',
    'remember_token' => 'abc',
];

$public = Arr::except($user, ['password', 'remember_token']);
// => ['id' => 42, 'name' => 'Bob', 'email' => '[email protected]']

Whitelist during a bulk insert

Applies Arr::only() to every row in a batch before inserting, ensuring extra fields injected by a malicious client are silently discarded.

Example · php
use Illuminate\Support\Arr;

$rows = [
    ['name' => 'Alice', 'email' => '[email protected]', 'admin' => true],
    ['name' => 'Bob',   'email' => '[email protected]', 'admin' => false],
];

$safe = array_map(
    fn($row) => Arr::only($row, ['name', 'email']),
    $rows
);

User::insert($safe); // 'admin' flag is never inserted

Discussion

  • Be the first to comment on this lesson.