Skip to content

[12.x] Add except method to Eloquent Builder #56442

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Aug 3, 2025

Conversation

achyutkneupane
Copy link
Contributor

@achyutkneupane achyutkneupane commented Jul 26, 2025

The except method in Illuminate\Database\Eloquent\Builder.php is added to exclude an object of Model or collection of Model in builder query.
Internally, it make use of whereKeyNot() method after extracting the key/keys of object or collection respectively.


Why not modified the whereKeyNot method?
Modifying whereKeyNot() to handle this would complicate its current responsibilities and potentially introduce unexpected behavior for existing consumers. Instead, this PR:

  • Keeps whereKeyNot() focused on keys/IDs
  • Adds a new expressive method, except(), for working directly with model instances

Usage

Before

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

After

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

@achyutkneupane achyutkneupane changed the title feat: Add except method to Eloquent Builder [12.x] Add except method to Eloquent Builder Jul 27, 2025
@taylorotwell taylorotwell merged commit 3acc32d into laravel:12.x Aug 3, 2025
60 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants