ModelQuery<T extends Model> class final

Model-aware query (Laravel's Eloquent Builder): wraps a QueryBuilder and hydrates models, applies global scopes and soft deletes, eager loads relations and offers whereHas / withCount.

Constructors

ModelQuery(ModelDefinition<T> definition, {DatabaseManager? db})
A query on the model of definition; Model.query() and the generated statics create it. Relations listed in the definition's with are eager loaded by default.

Properties

builder → QueryBuilder
The underlying builder (column-level operations delegate to it).
final
database → DatabaseManager
The database manager this query runs on.
no setter
definition → ModelDefinition<T>
The model's definition: table, key, casts, relations and scopes.
final
hashCode → int
The hash code for this object.
no setterinherited
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited
tableName → String
The name this query's table goes by: definition's table, or the alias of a self-relation subquery.
no setter

Methods

addSelect(List<Object> columns) → ModelQuery<T>
Adds columns to the selection.
aliasTable(String alias) → ModelQuery<T>
Gives the table an alias (FROM categories AS laravel_reserved_0), used by relation subqueries on the parent's own table. Soft deletes and key lookups are qualified with it.
avg(Object column) → Future<num?>
The average of column.
chunk(int size, FutureOr<Object?> callback(ModelCollection<T> models, int page)) → Future<void>
Calls callback with size models at a time and the page number, until the rows run out; a callback returning false stops it.
chunkById(int size, FutureOr<Object?> callback(ModelCollection<T> models)) → Future<void>
As chunk, paging by primary key instead of offset, so updating the rows inside callback cannot skip any.
count([Object column = '*']) → Future<int>
The number of matching models.
create([Map<String, Object?> attributes = const {}]) → Future<T>
Creates and saves a model.
createOrFirst(Map<String, Object?> attributes, [Map<String, Object?> values = const {}]) → Future<T>
Creates the row; when a unique index already holds it (another request won the race), returns the row matching attributes (Laravel's createOrFirst). Inside a transaction the insert runs in a savepoint, so a refused one leaves the transaction usable (PostgreSQL aborts it otherwise).
cursorPaginate({int? perPage, Cursor? cursor, String? path, String cursorName = 'cursor', Map<String, String> query = const {}}) → Future<CursorPaginator<T>>
A page of models after cursor (default: the request's ?cursor=), ordered by the query's order columns: fast on large tables, as no rows are skipped. Laravel's cursorPaginate JSON.
decrement(String column, [num amount = 1]) → Future<int>
Subtracts amount from column of the matching rows.
delete() → Future<int>
Bulk delete (soft delete when configured).
distinct() → ModelQuery<T>
Selects only distinct rows.
doesntExist() → Future<bool>
Whether no model matches.
doesntHave(String relation) → ModelQuery<T>
Models with no related row through relation.
exists() → Future<bool>
Whether any model matches.
find(Object id) → Future<T?>
The model with primary key id, or null.
findMany(List<Object?> ids) → Future<ModelCollection<T>>
The models whose primary keys are in ids.
findOrFail(Object id) → Future<T>
The model with primary key id; throws ModelNotFoundException (a 404) without one.
first() → Future<T?>
The first model, or null.
firstOrCreate(Map<String, Object?> attributes, [Map<String, Object?> values = const {}]) → Future<T>
The row matching attributes, or one created with values too; when another request creates it first, that row (through createOrFirst, as Laravel 12).
firstOrFail() → Future<T>
The first model; throws ModelNotFoundException (a 404) without one.
firstOrNew(Map<String, Object?> attributes, [Map<String, Object?> values = const {}]) → Future<T>
The first model matching attributes, or a new unsaved one with attributes and values.
forceDelete() → Future<int>
Deletes the matching rows for good, soft deleted ones included.
forPage(int page, [int? perPage]) → ModelQuery<T>
The models of page page (from 1), perPage defaulting to the model's perPage.
get() → Future<ModelCollection<T>>
Runs the query and returns the models, with eager loaded relations and withCount values.
groupBy(List<Object> columns) → ModelQuery<T>
GROUP BY columns.
has(String relation) → ModelQuery<T>
Models with at least one related row through relation.
having(Object column, String operator, Object? value) → ModelQuery<T>
A HAVING condition.
increment(String column, [num amount = 1]) → Future<int>
Adds amount to column of the matching rows.
inRandomOrder() → ModelQuery<T>
Random order.
join(String table, Object first, [String? operator, String? second]) → ModelQuery<T>
An inner join, as QueryBuilder.join. Models are hydrated from every selected column, so select the model's columns when joined columns clash.
latest([String? column]) → ModelQuery<T>
Newest first, by column or the model's created_at column.
lazy([int size = 500]) → Stream<T>
The models one at a time, read size rows per query.
leftJoin(String table, Object first, [String? operator, String? second]) → ModelQuery<T>
A left join, as QueryBuilder.leftJoin.
limit(int value) → ModelQuery<T>
At most value models.
loadRelationsOn(List<Model> models, Map<String, RelationConstraint?> wants, {bool autoload = false}) → Future<void>
Eager loads wants (possibly nested a.b.c) onto models.
lockForUpdate() → ModelQuery<T>
Locks the selected rows until the transaction ends (FOR UPDATE).
make([Map<String, Object?> attributes = const {}]) → T
Creates without saving.
max(Object column) → Future<Object?>
The largest value of column.
min(Object column) → Future<Object?>
The smallest value of column.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
offset(int value) → ModelQuery<T>
Skips the first value rows.
oldest([String? column]) → ModelQuery<T>
Oldest first, by column or the model's created_at column.
onlyTrashed() → ModelQuery<T>
Only soft deleted models.
orderBy(Object column, [String direction = 'asc']) → ModelQuery<T>
Orders by column, asc or desc.
orderByDesc(Object column) → ModelQuery<T>
Orders by column, descending.
orderByRaw(String sql, [List<Object?> bindings = const []]) → ModelQuery<T>
Orders by raw SQL: sql is used as written, so values go in bindings.
orderByVectorDistance(String column, List<num> vector) → ModelQuery<T>
QueryBuilder.orderByVectorDistance.
orWhere(Object column, [Object? operatorOrValue, Object? value]) → ModelQuery<T>
where joined with OR.
orWhereAfterToday(Object columns) → ModelQuery<T>
whereAfterToday joined with OR.
orWhereBeforeToday(Object columns) → ModelQuery<T>
whereBeforeToday joined with OR.
orWhereDoesntHave(String relation, [RelationConstraint? constraint]) → ModelQuery<T>
whereDoesntHave joined with OR.
orWhereDoesntHaveMorph(String relation, List<ModelDefinition<Model>> types, [MorphConstraint? constraint]) → ModelQuery<T>
whereDoesntHaveMorph joined with OR.
orWhereFuture(Object columns) → ModelQuery<T>
whereFuture joined with OR.
orWhereHas(String relation, [RelationConstraint? constraint]) → ModelQuery<T>
whereHas joined with OR.
orWhereHasMorph(String relation, List<ModelDefinition<Model>> types, [MorphConstraint? constraint]) → ModelQuery<T>
whereHasMorph joined with OR.
orWhereNowOrFuture(Object columns) → ModelQuery<T>
whereNowOrFuture joined with OR.
orWhereNowOrPast(Object columns) → ModelQuery<T>
whereNowOrPast joined with OR.
orWherePast(Object columns) → ModelQuery<T>
wherePast joined with OR.
orWhereToday(Object columns) → ModelQuery<T>
whereToday joined with OR.
orWhereTodayOrAfter(Object columns) → ModelQuery<T>
whereTodayOrAfter joined with OR.
orWhereTodayOrBefore(Object columns) → ModelQuery<T>
whereTodayOrBefore joined with OR.
paginate({int? page, int? perPage, String? path, String pageName = 'page', Map<String, String> query = const {}}) → Future<LengthAwarePaginator<T>>
A page of models with the total count, in Laravel's paginator JSON; perPage defaults to the model's perPage, page to the request's ?page=.
pluck(String column, [String? key]) → Future<Object>
The values of column: a list, or a map keyed by key when given.
prepared() → QueryBuilder
The builder with global scopes, soft deletes and withCount applied.
restore() → Future<int>
Restores the matching soft deleted models.
scope(String name, [List<Object?> args = const []]) → ModelQuery<T>
Applies the local scope name (scopes: in the definition).
select(List<Object> columns) → ModelQuery<T>
Replaces the selected columns.
selectRaw(String sql, [List<Object?> bindings = const []]) → ModelQuery<T>
Adds a raw select expression with ? bindings.
selectVector(String column) → ModelQuery<T>
QueryBuilder.selectVector.
sharedLock() → ModelQuery<T>
A shared lock on the selected rows.
simplePaginate({int? page, int? perPage, String? path, String pageName = 'page', Map<String, String> query = const {}}) → Future<SimplePaginator<T>>
A page of models without counting the total: links to the next and previous page only.
skip(int value) → ModelQuery<T>
Laravel's alias of offset.
sole() → Future<T>
The only matching model; throws ModelNotFoundException without one and MultipleRecordsFoundException with more.
sum(Object column) → Future<num?>
The sum of column.
take(int value) → ModelQuery<T>
Laravel's alias of limit.
tap(void callback(ModelQuery<T> query)) → ModelQuery<T>
Calls callback with the query and returns it.
toSql() → String
The SQL this query runs, with ? placeholders, for debugging.
toString() → String
A string representation of this object.
inherited
update(Map<String, Object?> values) → Future<int>
Bulk update (adds updated_at).
updateOrCreate(Map<String, Object?> attributes, Map<String, Object?> values) → Future<T>
The row matching attributes updated with values, or created with both; safe against a concurrent create (Laravel 12's updateOrCreate).
when(bool condition, void callback(ModelQuery<T> query), [void otherwise(ModelQuery<T> query)?]) → ModelQuery<T>
Applies callback only when condition is true (else otherwise): query.when(search != null, (q) => q.whereLike('name', '%$search%')).
where(Object column, [Object? operatorOrValue, Object? value]) → ModelQuery<T>
where('col', value), where('col', '>', value), a map of columns to values, or a closure for a nested group, as QueryBuilder.where.
whereAfterToday(Object columns) → ModelQuery<T>
Rows whose columns are after today.
whereAny(List<String> columns, String operator, Object? value) → ModelQuery<T>
Rows where any of columns matches: whereAny(['name', 'email'], 'like', '%ana%').
whereBeforeToday(Object columns) → ModelQuery<T>
Rows whose columns are before today.
whereBetween(String column, Object? from, Object? to) → ModelQuery<T>
column BETWEEN from AND to.
whereColumn(String first, String operator, String second) → ModelQuery<T>
Compares two columns: whereColumn('updated_at', '>', 'created_at').
whereDate(String column, String operatorOrValue, [Object? value]) → ModelQuery<T>
Compares the date part of a datetime column.
whereDay(String column, Object operatorOrValue, [Object? value]) → ModelQuery<T>
Compares the day of the month of a date column.
whereDoesntHave(String relation, [RelationConstraint? constraint]) → ModelQuery<T>
Models with no related row matching constraint through relation.
whereDoesntHaveMorph(String relation, List<ModelDefinition<Model>> types, [MorphConstraint? constraint]) → ModelQuery<T>
Rows whose MorphTo owner is one of types but does not match constraint (or no longer exists).
whereFuture(Object columns) → ModelQuery<T>
Rows whose columns are after now.
whereHas(String relation, [RelationConstraint? constraint, String boolean = 'AND']) → ModelQuery<T>
Filters on the existence of related rows. relation may be nested (posts.comments): each level becomes an EXISTS inside the previous one, and constraint applies to the last.
whereHasMorph(String relation, List<ModelDefinition<Model>> types, [MorphConstraint? constraint]) → ModelQuery<T>
Filters on a MorphTo relation whose owner is one of types and matches constraint (called with each type).
whereIn(String column, Object values) → ModelQuery<T>
column IN (...) for a list, or for a subquery's rows.
whereKey(Object? key) → ModelQuery<T>
Rows whose primary key is key.
whereKeyNot(Object? key) → ModelQuery<T>
Rows whose primary key is not key.
whereLike(String column, String pattern, {bool caseSensitive = false}) → ModelQuery<T>
column LIKE pattern, case-insensitive unless asked otherwise.
whereMonth(String column, Object operatorOrValue, [Object? value]) → ModelQuery<T>
Compares the month of a date column.
whereNotIn(String column, Object values) → ModelQuery<T>
column NOT IN (...).
whereNotNull(String column) → ModelQuery<T>
column IS NOT NULL.
whereNowOrFuture(Object columns) → ModelQuery<T>
Rows whose columns are now or later.
whereNowOrPast(Object columns) → ModelQuery<T>
Rows whose columns are now or earlier.
whereNull(String column) → ModelQuery<T>
column IS NULL.
wherePast(Object columns) → ModelQuery<T>
Rows whose columns are before now (Clock.now()).
whereRaw(String sql, [List<Object?> bindings = const []]) → ModelQuery<T>
A raw condition with ? bindings. Never interpolate input into sql.
whereToday(Object columns) → ModelQuery<T>
Rows whose columns fall on today's date.
whereTodayOrAfter(Object columns) → ModelQuery<T>
Rows whose columns are today or later.
whereTodayOrBefore(Object columns) → ModelQuery<T>
Rows whose columns are today or earlier.
whereVectorSimilarTo(String column, List<num> vector, {double minSimilarity = 0.6, bool order = true}) → ModelQuery<T>
QueryBuilder.whereVectorSimilarTo.
whereYear(String column, Object operatorOrValue, [Object? value]) → ModelQuery<T>
Compares the year of a date column.
with_(Object relations) → ModelQuery<T>
Eager loads relations: with(['posts', 'posts.comments']) or with({'posts': (q) => q.where('published', true)}).
withAvg(Object relations, String column) → ModelQuery<T>
Adds <relation>_avg_<column> columns.
withCount(Object relations) → ModelQuery<T>
Adds <relation>_count columns ('posts as drafts_count' names the column).
withExists(Object relations) → ModelQuery<T>
Adds boolean <relation>_exists columns.
withMax(Object relations, String column) → ModelQuery<T>
Adds <relation>_max_<column> columns.
withMin(Object relations, String column) → ModelQuery<T>
Adds <relation>_min_<column> columns.
withoutGlobalScope(String name) → ModelQuery<T>
Leaves out the global scope named name for this query.
withoutGlobalScopes([List<String>? names]) → ModelQuery<T>
Without every global scope, soft deletes included; with names, only those of namedGlobalScopes.
withoutTrashed() → ModelQuery<T>
Leaves out soft deleted models again after withTrashed.
withRelationshipAutoloading() → ModelQuery<T>
Model.automaticallyEagerLoad for the results of this query.
withSum(Object relations, String column) → ModelQuery<T>
Adds <relation>_sum_<column> columns.
withTrashed() → ModelQuery<T>
Includes soft deleted models.
withWhereHas(String relation, [RelationConstraint? constraint]) → ModelQuery<T>
whereHas + with with the same constraint.

Operators

operator ==(Object other) → bool
The equality operator.
inherited

Static Methods

parseWith(Object relations) → Map<String, RelationConstraint?>
Parses with() arguments into name → constraint pairs.