Use whereKey() and whereKeyNot() to query model primary keys automatically without hardcoding 'id' column names.
Models with custom primary keys (such as protected $primaryKey = 'uuid'; or 'account_id') can break queries if you hardcode where('id', $key) or whereIn('id', $keys).
whereKey() and whereKeyNot() automatically query the model's configured primary key column.
Querying by Single Key or Array of Keys
use App\Models\Order;
// Resolves automatically to: WHERE order_id = 42
$order = Order::whereKey(42)->first();
// Resolves automatically to: WHERE order_id IN (1, 2, 3)
$orders = Order::whereKey([1, 2, 3])->get();
Excluding Primary Keys with whereKeyNot()
// Find all active users except the current authenticated user
$otherUsers = User::whereKeyNot(auth()->id())
->where('is_active', true)
->get();
Summary
- Automatically respects custom
$primaryKeymodel configurations. - Accepts single IDs, arrays of IDs, or Eloquent collections.
whereKeyNot()cleanly excludes primary key matches.
Related Tips
View all tips →Scope Pivot Table Queries with Closures in wherePivot() in Laravel 13.26
Laravel 13.26 allows wherePivot() and orWherePivot() to accept closures, enabling direct reuse of local scopes defined on custom Pivot models.
Simplify Chronological Query Sorting with latest() and oldest()
Replace verbose orderBy('created_at', 'desc') clauses with the clean latest() and oldest() query builder helpers.