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'swithare 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
callbackwithsizemodels at a time and the page number, until the rows run out; a callback returningfalsestops 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
callbackcannot 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'screateOrFirst). 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'scursorPaginateJSON. -
decrement(
String column, [num amount = 1]) → Future< int> -
Subtracts
amountfromcolumnof 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 withvaluestoo; 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 withattributesandvalues. -
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),perPagedefaulting to the model'sperPage. -
get(
) → Future< ModelCollection< T> > -
Runs the query and returns the models, with eager loaded relations and
withCountvalues. -
groupBy(
List< Object> columns) → ModelQuery<T> -
GROUP BYcolumns. -
has(
String relation) → ModelQuery< T> -
Models with at least one related row through
relation. -
having(
Object column, String operator, Object? value) → ModelQuery< T> -
A
HAVINGcondition. -
increment(
String column, [num amount = 1]) → Future< int> -
Adds
amounttocolumnof 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
columnor the model'screated_atcolumn. -
lazy(
[int size = 500]) → Stream< T> -
The models one at a time, read
sizerows 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
valuemodels. -
loadRelationsOn(
List< Model> models, Map<String, RelationConstraint?> wants, {bool autoload = false}) → Future<void> -
Eager loads
wants(possibly nesteda.b.c) ontomodels. -
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
valuerows. -
oldest(
[String? column]) → ModelQuery< T> -
Oldest first, by
columnor the model'screated_atcolumn. -
onlyTrashed(
) → ModelQuery< T> - Only soft deleted models.
-
orderBy(
Object column, [String direction = 'asc']) → ModelQuery< T> -
Orders by
column,ascordesc. -
orderByDesc(
Object column) → ModelQuery< T> -
Orders by
column, descending. -
orderByRaw(
String sql, [List< Object?> bindings = const []]) → ModelQuery<T> -
Orders by raw SQL:
sqlis used as written, so values go inbindings. -
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< types, [MorphConstraint? constraint]) → ModelQuery<Model> >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< types, [MorphConstraint? constraint]) → ModelQuery<Model> >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;
perPagedefaults to the model'sperPage,pageto the request's?page=. -
pluck(
String column, [String? key]) → Future< Object> -
The values of
column: a list, or a map keyed bykeywhen 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.
- 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
MultipleRecordsFoundExceptionwith 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
callbackwith 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
attributesupdated withvalues, or created with both; safe against a concurrent create (Laravel 12'supdateOrCreate). -
when(
bool condition, void callback(ModelQuery< T> query), [void otherwise(ModelQuery<T> query)?]) → ModelQuery<T> -
Applies
callbackonly whenconditionis true (elseotherwise):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
columnsare after today. -
whereAny(
List< String> columns, String operator, Object? value) → ModelQuery<T> -
Rows where any of
columnsmatches:whereAny(['name', 'email'], 'like', '%ana%'). -
whereBeforeToday(
Object columns) → ModelQuery< T> -
Rows whose
columnsare 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
constraintthroughrelation. -
whereDoesntHaveMorph(
String relation, List< ModelDefinition< types, [MorphConstraint? constraint]) → ModelQuery<Model> >T> -
Rows whose
MorphToowner is one oftypesbut does not matchconstraint(or no longer exists). -
whereFuture(
Object columns) → ModelQuery< T> -
Rows whose
columnsare after now. -
whereHas(
String relation, [RelationConstraint? constraint, String boolean = 'AND']) → ModelQuery< T> -
Filters on the existence of related rows.
relationmay be nested (posts.comments): each level becomes anEXISTSinside the previous one, andconstraintapplies to the last. -
whereHasMorph(
String relation, List< ModelDefinition< types, [MorphConstraint? constraint]) → ModelQuery<Model> >T> -
Filters on a
MorphTorelation whose owner is one oftypesand matchesconstraint(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
columnsare now or later. -
whereNowOrPast(
Object columns) → ModelQuery< T> -
Rows whose
columnsare now or earlier. -
whereNull(
String column) → ModelQuery< T> -
column IS NULL. -
wherePast(
Object columns) → ModelQuery< T> -
Rows whose
columnsare before now (Clock.now()). -
whereRaw(
String sql, [List< Object?> bindings = const []]) → ModelQuery<T> -
A raw condition with
?bindings. Never interpolate input intosql. -
whereToday(
Object columns) → ModelQuery< T> -
Rows whose
columnsfall on today's date. -
whereTodayOrAfter(
Object columns) → ModelQuery< T> -
Rows whose
columnsare today or later. -
whereTodayOrBefore(
Object columns) → ModelQuery< T> -
Rows whose
columnsare 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'])orwith({'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>_countcolumns ('posts as drafts_count'names the column). -
withExists(
Object relations) → ModelQuery< T> -
Adds boolean
<relation>_existscolumns. -
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
namefor this query. -
withoutGlobalScopes(
[List< String> ? names]) → ModelQuery<T> -
Without every global scope, soft deletes included; with
names, only those ofnamedGlobalScopes. -
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+withwith the same constraint.
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited
Static Methods
-
parseWith(
Object relations) → Map< String, RelationConstraint?> -
Parses
with()arguments intoname → constraintpairs.