Exclude Models With except() Method in Laravel 12.22

laravel
release
eloquent
Nabil Hassen
Nabil Hassen
Aug 8, 2025
Exclude Models With except() Method in Laravel 12.22
Last updated on Aug 8, 2025
Table of contents:

Laravel 12.22 - Adds except() Method to Eloquent Builder for Excluding Models from Queries

Laravel 12.22 introduces a new and expressive method called except() on the Eloquent query builder. This method makes it easy to exclude specific model instances or collections of models from your query results — helping you write cleaner, more readable code.

What Does except() Do?

The except() method allows you to exclude one or more model instances or collections of models from a query. Internally, it leverages the existing whereKeyNot() method by extracting the primary keys from the given models.

This means instead of manually extracting IDs and calling whereKeyNot(), you can now directly pass models or collections to except() for exclusion.

Why Not Modify whereKeyNot()?

whereKeyNot() was originally designed to exclude records by their key or IDs only. Modifying it to handle models or collections directly would complicate its purpose and could introduce unexpected side effects for existing users.

The new except() method keeps concerns clean:

  • whereKeyNot() remains focused on keys/IDs.
  • except() provides a user-friendly, expressive way to exclude models.

How to Use except()

Before Laravel 12.22

To exclude videos with IDs 2 and 4, you would:

$videos = \App\Models\Video::query()
->whereIn('id', [2, 4])
->get();
 
$otherVideosUsingWhereKeyNot = \App\Models\Video::query()
->whereKeyNot($videos->pluck('id'))
->get();

Here you manually pluck the IDs from the collection to exclude them.

After Laravel 12.22

You can simplify the above by passing the models directly to except():

$videos = \App\Models\Video::query()
->whereIn('id', [2, 4])
->get();
 
$otherVideosUsingExcept = \App\Models\Video::query()
->except($videos)
->get();

This makes your intentions clearer and your code cleaner.

Summary

The new except() method in Laravel 12.22 is a small addition to Eloquent, improving readability and expressiveness when excluding models from queries.

  • Pass one or many model instances or collections to exclude them.
  • Internally uses whereKeyNot() for efficient query filtering.
  • Keeps whereKeyNot() focused and unaltered.
  • Available now in Laravel 12.22 and later.
  • This method was contributed in Pull Request #56442
Nabil Hassen
Nabil Hassen
Full Stack Web Developer

Stay Updated.

I'll you email you as soon as new, fresh content is published.

Thanks for subscribing to my blog.

Latest Posts