@orieljs/database 0.1.0-alpha.1 → 0.1.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { OrielError, ModelNotFoundError as ModelNotFoundError$1, DriverName, DatabaseConnection, Row, QueryBuilder, Operator, DatabaseManager, Token, ModelInstance, Application, ConsoleKernel, RouteModelResolver, Class } from '@orieljs/contracts';
1
+ import { OrielError, ModelNotFoundError as ModelNotFoundError$1, DriverName, DatabaseConnection, Row, QueryBuilder, Operator, DatabaseManager, Token, ModelInstance, DatabaseNotification as DatabaseNotification$1, Application, ConsoleKernel, RouteModelResolver, Class } from '@orieljs/contracts';
2
2
  import { SqliteDatabase, SqliteStatement, Dialect, RawBuilder, Kysely, CompiledQuery, QueryResult } from 'kysely';
3
- import { Collection, LazyCollection } from '@orieljs/collections';
3
+ import { Collection, LazyCollection, Operator as Operator$1 } from '@orieljs/collections';
4
4
  import * as _orieljs_support from '@orieljs/support';
5
5
  import { ServiceProvider } from '@orieljs/support';
6
6
 
@@ -154,6 +154,8 @@ interface ColumnAttributes {
154
154
  after?: string;
155
155
  first?: boolean;
156
156
  onUpdate?: Expression;
157
+ /** Set by change(): the column exists and is redefined, not added. */
158
+ change?: boolean;
157
159
  }
158
160
  /** A column in a Blueprint, with Laravel's fluent modifiers: t.string('email').nullable().unique(). */
159
161
  declare class ColumnDefinition {
@@ -179,6 +181,12 @@ declare class ColumnDefinition {
179
181
  first(): this;
180
182
  /** default CURRENT_TIMESTAMP. */
181
183
  useCurrent(): this;
184
+ /**
185
+ * Redefines an existing column (Laravel's change()): t.string('title', 500).nullable().change(). As in Laravel 11+,
186
+ * the column becomes exactly this definition: a modifier it had and that isn't given again (nullable, default,
187
+ * comment, …) is dropped. On SQLite the table is rebuilt.
188
+ */
189
+ change(): this;
182
190
  /** MySQL only: on update CURRENT_TIMESTAMP. */
183
191
  useCurrentOnUpdate(): this;
184
192
  }
@@ -239,8 +247,12 @@ type BlueprintCommand = {
239
247
  from: string;
240
248
  to: string;
241
249
  } | {
242
- name: 'dropPrimary' | 'dropUnique' | 'dropIndex' | 'dropForeign';
250
+ name: 'dropPrimary' | 'dropUnique' | 'dropIndex';
243
251
  index: string;
252
+ } | {
253
+ name: 'dropForeign';
254
+ index: string;
255
+ columns?: string[];
244
256
  } | {
245
257
  name: 'rename';
246
258
  to: string;
@@ -313,6 +325,7 @@ declare class Blueprint {
313
325
  /** By name, or by columns (the conventional {table}_{columns}_unique name). */
314
326
  dropUnique(index: string | string[]): void;
315
327
  dropIndex(index: string | string[]): void;
328
+ /** By name, or by columns (the conventional name; SQLite needs the columns, it doesn't keep foreign key names). */
316
329
  dropForeign(index: string | string[]): void;
317
330
  /** Drops the foreign key on the column, then the column. */
318
331
  dropConstrainedForeignId(column: string): void;
@@ -323,6 +336,10 @@ declare class Blueprint {
323
336
  rename(to: string): void;
324
337
  drop(): void;
325
338
  dropIfExists(): void;
339
+ /** The columns this blueprint adds (not the ones change() redefines). */
340
+ addedColumns(): ColumnDefinition[];
341
+ /** The existing columns change() redefines (on a table being created, every column is added instead). */
342
+ changedColumns(): ColumnDefinition[];
326
343
  /** Laravel's default index name: {table}_{columns}_{type}, lowercased, with - and . replaced by _. */
327
344
  createIndexName(type: IndexType | 'foreign', columns: string[]): string;
328
345
  /** The index commands implied by column modifiers (t.string('email').unique()), in column order. */
@@ -343,6 +360,42 @@ interface ColumnInfo {
343
360
  default: string | null;
344
361
  auto_increment: boolean;
345
362
  }
363
+ /** One index of an existing table, as reported by Schema.getIndexes() (Laravel's shape). */
364
+ interface IndexInfo {
365
+ /** Lower-cased. The primary key is 'primary' on MySQL and on a SQLite rowid table, `{table}_pkey` on Postgres. */
366
+ name: string;
367
+ columns: string[];
368
+ /** The index method ('btree', 'hash', …) on Postgres and MySQL; null on SQLite. */
369
+ type: string | null;
370
+ unique: boolean;
371
+ primary: boolean;
372
+ }
373
+ /** One foreign key of an existing table, as reported by Schema.getForeignKeys() (Laravel's shape). */
374
+ interface ForeignKeyInfo {
375
+ /** The constraint name; null on SQLite, which doesn't keep it. */
376
+ name: string | null;
377
+ columns: string[];
378
+ foreign_schema: string;
379
+ foreign_table: string;
380
+ /** Empty when a SQLite key names only the table (it then points at that table's primary key). */
381
+ foreign_columns: string[];
382
+ /** 'cascade', 'restrict', 'set null', 'set default' or 'no action'. */
383
+ on_update: string;
384
+ on_delete: string;
385
+ }
386
+ /**
387
+ * A step a blueprint can't express as fixed SQL: on SQLite, rebuilding the table from its live definition plus these
388
+ * key commands and changed columns. SchemaBuilder.build() runs it (Schema/SqliteTableRebuild.ts).
389
+ */
390
+ interface TableRebuild {
391
+ readonly kind: 'rebuild';
392
+ readonly table: string;
393
+ readonly commands: BlueprintCommand[];
394
+ readonly changes: ColumnDefinition[];
395
+ }
396
+ /** One step of a compiled blueprint: a statement, or a table rebuild. */
397
+ type SchemaStep = Sql$1 | TableRebuild;
398
+ declare const isTableRebuild: (step: SchemaStep) => step is TableRebuild;
346
399
  /**
347
400
  * Turns a Blueprint into DDL for one driver (Laravel's Schema\Grammars). Identifiers go through sql.id();
348
401
  * default values and comments are quoted literals (sql.lit); only DB.raw() defaults are written as-is.
@@ -352,11 +405,18 @@ declare abstract class SchemaGrammar {
352
405
  abstract readonly driver: DriverName;
353
406
  constructor(config?: Partial<ConnectionConfig>);
354
407
  static for(driver: DriverName, config?: Partial<ConnectionConfig>): SchemaGrammar;
355
- /** Every statement for the blueprint: create/add first, then commands in order, then indexes from column modifiers. */
408
+ /**
409
+ * Every statement for the blueprint: create/add first, then commands in order, then indexes from column modifiers.
410
+ * A blueprint that can only run against the live table (a SQLite rebuild) throws: run it with Schema.table().
411
+ */
356
412
  compile(blueprint: Blueprint): Sql$1[];
413
+ /** compile() with table rebuilds as steps of their own; consecutive rebuilds of one run are merged into one. */
414
+ compileSteps(blueprint: Blueprint): SchemaStep[];
357
415
  protected compileCreate(blueprint: Blueprint, _commands: BlueprintCommand[], _handled: Set<BlueprintCommand>): Sql$1;
358
416
  protected compileAdd(blueprint: Blueprint, _commands: BlueprintCommand[], _handled: Set<BlueprintCommand>): Sql$1[];
359
- protected compileCommand(blueprint: Blueprint, command: BlueprintCommand): Sql$1[];
417
+ /** Redefines an existing column (change()). */
418
+ protected abstract compileChange(blueprint: Blueprint, column: ColumnDefinition): SchemaStep[];
419
+ protected compileCommand(blueprint: Blueprint, command: BlueprintCommand): SchemaStep[];
360
420
  compileRename(from: string, to: string): Sql$1;
361
421
  compileDrop(table: string): Sql$1;
362
422
  compileDropIfExists(table: string): Sql$1;
@@ -383,16 +443,28 @@ declare abstract class SchemaGrammar {
383
443
  abstract compileTables(): Sql$1;
384
444
  abstract compileColumns(table: string): Sql$1;
385
445
  abstract normalizeColumns(rows: Array<Record<string, unknown>>, tableSql?: string): ColumnInfo[];
446
+ abstract compileIndexes(table: string): Sql$1;
447
+ abstract normalizeIndexes(rows: Array<Record<string, unknown>>): IndexInfo[];
448
+ abstract compileForeignKeys(table: string): Sql$1;
449
+ abstract normalizeForeignKeys(rows: Array<Record<string, unknown>>): ForeignKeyInfo[];
386
450
  abstract compileEnableForeignKeyConstraints(): Sql$1;
387
451
  abstract compileDisableForeignKeyConstraints(): Sql$1;
388
452
  }
389
453
  declare class SqliteSchemaGrammar extends SchemaGrammar {
390
454
  readonly driver: "sqlite";
391
- /** SQLite can't add keys to an existing table, so primary and foreign keys go inside create table. */
455
+ /** A new table's primary and foreign keys go inside create table (adding them later rebuilds the table). */
392
456
  protected compileCreate(blueprint: Blueprint, commands: BlueprintCommand[], handled: Set<BlueprintCommand>): Sql$1;
393
457
  /** New columns may carry an inline `references` clause (the only foreign key SQLite can add later). */
394
458
  protected compileAdd(blueprint: Blueprint, commands: BlueprintCommand[], handled: Set<BlueprintCommand>): Sql$1[];
395
- protected compileCommand(blueprint: Blueprint, command: BlueprintCommand): Sql$1[];
459
+ /**
460
+ * SQLite can't add or drop a primary or foreign key on an existing table: those commands rebuild the table (Laravel
461
+ * 11+'s compileAlter), as a step SchemaBuilder.build() runs against the live table.
462
+ */
463
+ protected compileCommand(blueprint: Blueprint, command: BlueprintCommand): SchemaStep[];
464
+ /** SQLite can't alter a column: changing one rebuilds the table with the new definition. */
465
+ protected compileChange(blueprint: Blueprint, column: ColumnDefinition): SchemaStep[];
466
+ /** `foreign key (…) references … on delete …`, a table constraint of a rebuilt table. */
467
+ compileForeignKeyConstraint(foreign: ForeignKeyDefinition): Sql$1;
396
468
  protected compileUnique(blueprint: Blueprint, index: string, columns: string[]): Sql$1;
397
469
  protected compileDropUnique(_blueprint: Blueprint, index: string): Sql$1;
398
470
  protected type(column: ColumnDefinition): Sql$1;
@@ -400,17 +472,34 @@ declare class SqliteSchemaGrammar extends SchemaGrammar {
400
472
  compileTables(): Sql$1;
401
473
  compileColumns(table: string): Sql$1;
402
474
  normalizeColumns(rows: Array<Record<string, unknown>>): ColumnInfo[];
475
+ /** Laravel's query: the primary key from pragma_table_xinfo, then every index of pragma_index_list with its columns. */
476
+ compileIndexes(table: string): Sql$1;
477
+ /** A table whose primary key has its own index (not a rowid alias) lists it twice: the index entry is kept. */
478
+ normalizeIndexes(rows: Array<Record<string, unknown>>): IndexInfo[];
479
+ compileForeignKeys(table: string): Sql$1;
480
+ normalizeForeignKeys(rows: Array<Record<string, unknown>>): ForeignKeyInfo[];
403
481
  compileEnableForeignKeyConstraints(): Sql$1;
404
482
  compileDisableForeignKeyConstraints(): Sql$1;
405
483
  }
406
484
  declare class PostgresSchemaGrammar extends SchemaGrammar {
407
485
  readonly driver: "pgsql";
486
+ /** A changed column's comment is set again, or cleared (`is NULL`) when the new definition has none (Laravel 11+). */
408
487
  protected compileComments(blueprint: Blueprint): Sql$1[];
488
+ /**
489
+ * Laravel's compileChange(): `alter column` for the type, the nullability and the default, in one statement. A serial
490
+ * type becomes its integer type (the sequence stays), and an auto-increment column keeps its default. No `using`
491
+ * clause: a change Postgres can't cast implicitly fails, as in Laravel.
492
+ */
493
+ protected compileChange(blueprint: Blueprint, column: ColumnDefinition): SchemaStep[];
409
494
  protected type(column: ColumnDefinition): Sql$1;
410
495
  protected modifiers(column: ColumnDefinition): Sql$1[];
411
496
  compileTables(): Sql$1;
412
497
  compileColumns(table: string): Sql$1;
413
498
  normalizeColumns(rows: Array<Record<string, unknown>>): ColumnInfo[];
499
+ compileIndexes(table: string): Sql$1;
500
+ normalizeIndexes(rows: Array<Record<string, unknown>>): IndexInfo[];
501
+ compileForeignKeys(table: string): Sql$1;
502
+ normalizeForeignKeys(rows: Array<Record<string, unknown>>): ForeignKeyInfo[];
414
503
  compileEnableForeignKeyConstraints(): Sql$1;
415
504
  compileDisableForeignKeyConstraints(): Sql$1;
416
505
  }
@@ -418,6 +507,8 @@ declare class MySqlSchemaGrammar extends SchemaGrammar {
418
507
  readonly driver: "mysql";
419
508
  protected compileCreate(blueprint: Blueprint, commands: BlueprintCommand[], handled: Set<BlueprintCommand>): Sql$1;
420
509
  protected compileAdd(blueprint: Blueprint): Sql$1[];
510
+ /** Laravel's compileChange(): `modify` with the column's whole new definition. */
511
+ protected compileChange(blueprint: Blueprint, column: ColumnDefinition): SchemaStep[];
421
512
  protected compileUnique(blueprint: Blueprint, index: string, columns: string[]): Sql$1;
422
513
  protected compileIndex(blueprint: Blueprint, index: string, columns: string[]): Sql$1;
423
514
  protected compileDropPrimary(blueprint: Blueprint): Sql$1;
@@ -429,6 +520,10 @@ declare class MySqlSchemaGrammar extends SchemaGrammar {
429
520
  compileTables(): Sql$1;
430
521
  compileColumns(table: string): Sql$1;
431
522
  normalizeColumns(rows: Array<Record<string, unknown>>): ColumnInfo[];
523
+ compileIndexes(table: string): Sql$1;
524
+ normalizeIndexes(rows: Array<Record<string, unknown>>): IndexInfo[];
525
+ compileForeignKeys(table: string): Sql$1;
526
+ normalizeForeignKeys(rows: Array<Record<string, unknown>>): ForeignKeyInfo[];
432
527
  compileEnableForeignKeyConstraints(): Sql$1;
433
528
  compileDisableForeignKeyConstraints(): Sql$1;
434
529
  }
@@ -451,7 +546,10 @@ declare class SchemaBuilder {
451
546
  drop(table: string): Promise<void>;
452
547
  dropIfExists(table: string): Promise<void>;
453
548
  rename(from: string, to: string): Promise<void>;
454
- /** Runs a blueprint's statements. Also useful to inspect the DDL: grammar.compile(blueprint). */
549
+ /**
550
+ * Runs a blueprint's statements in order (inspect them with grammar.compile(blueprint)). On SQLite, a change to the
551
+ * keys of an existing table rebuilds it from its live definition at its place in that order.
552
+ */
455
553
  build(blueprint: Blueprint): Promise<void>;
456
554
  /** The table names of the connection's database (or current schema on Postgres). */
457
555
  getTables(): Promise<string[]>;
@@ -461,6 +559,16 @@ declare class SchemaBuilder {
461
559
  /** Case-insensitive, like Laravel. */
462
560
  hasColumn(table: string, column: string): Promise<boolean>;
463
561
  hasColumns(table: string, columns: string[]): Promise<boolean>;
562
+ /** The table's indexes, its primary key included (Laravel's getIndexes()). */
563
+ getIndexes(table: string): Promise<IndexInfo[]>;
564
+ getIndexListing(table: string): Promise<string[]>;
565
+ /**
566
+ * Whether the table has an index with this name, or on exactly these columns (in order). `type` narrows it:
567
+ * 'primary', 'unique', or an index method such as 'btree'.
568
+ */
569
+ hasIndex(table: string, index: string | string[], type?: string): Promise<boolean>;
570
+ /** The table's foreign keys (Laravel's getForeignKeys()). */
571
+ getForeignKeys(table: string): Promise<ForeignKeyInfo[]>;
464
572
  enableForeignKeyConstraints(): Promise<void>;
465
573
  disableForeignKeyConstraints(): Promise<void>;
466
574
  /**
@@ -595,8 +703,11 @@ declare abstract class AbstractPaginator<T> implements Iterable<T> {
595
703
  items(): T[];
596
704
  getCollection(): Collection<T>;
597
705
  setCollection(items: Collection<T>): this;
598
- /** Transforms each item in place, typically for serialization: paginator.through(post => ({ id: post.id })). */
599
- through(callback: (item: T, index: number) => unknown): this;
706
+ /**
707
+ * Transforms each item in place, typically for serialization, and returns this paginator typed with the new items:
708
+ * `posts.through((post) => ({ id: post.id }))`. Each paginator narrows the return type to its own class.
709
+ */
710
+ through<U>(callback: (item: T, index: number) => U): AbstractPaginator<U>;
600
711
  perPage(): number;
601
712
  count(): number;
602
713
  isEmpty(): boolean;
@@ -642,6 +753,7 @@ declare class CursorPaginator<T> extends AbstractPaginator<T> {
642
753
  static resolveCurrentCursor(cursorName?: string): Cursor | undefined;
643
754
  cursor(): Cursor | undefined;
644
755
  getCursorName(): string;
756
+ through<U>(callback: (item: T, index: number) => U): CursorPaginator<U>;
645
757
  hasMorePages(): boolean;
646
758
  onFirstPage(): boolean;
647
759
  nextCursor(): Cursor | undefined;
@@ -671,12 +783,16 @@ declare class LengthAwarePaginator<T> extends AbstractPaginator<T> {
671
783
  protected readonly lastPageValue: number;
672
784
  constructor(items: Iterable<T>, totalValue: number, perPage: number, currentPage?: number, options?: PaginatorOptions);
673
785
  total(): number;
786
+ through<U>(callback: (item: T, index: number) => U): LengthAwarePaginator<U>;
674
787
  lastPage(): number;
675
788
  hasPages(): boolean;
676
789
  hasMorePages(): boolean;
677
790
  onLastPage(): boolean;
678
791
  nextPageUrl(): string | null;
679
- /** The page links Laravel renders: previous, the page window with '...' gaps, next. */
792
+ /**
793
+ * The page links Laravel renders: previous, the page window with '...' gaps, next. The labels are plain text
794
+ * ("« Previous", "Next »"), not Laravel's `&laquo;` entities, so a page can print them as text.
795
+ */
680
796
  linkCollection(): PaginationLink[];
681
797
  /** Laravel's UrlWindow: the first pages, the slider around the current page and the last pages, with '...' between. */
682
798
  protected elements(): Array<UrlRange | '...'>;
@@ -693,6 +809,7 @@ declare class Paginator<T> extends AbstractPaginator<T> {
693
809
  protected readonly hasMore: boolean;
694
810
  constructor(items: Iterable<T>, perPage: number, currentPage?: number, options?: PaginatorOptions);
695
811
  hasMorePages(): boolean;
812
+ through<U>(callback: (item: T, index: number) => U): Paginator<U>;
696
813
  hasPages(): boolean;
697
814
  onLastPage(): boolean;
698
815
  nextPageUrl(): string | null;
@@ -723,6 +840,20 @@ declare class Grammar {
723
840
  compileOrders(query: Builder$1<unknown>): Sql | undefined;
724
841
  compileWheres(wheres: readonly Where[], keyword?: 'where' | 'on'): Sql | undefined;
725
842
  compileWhere(where: Where): Sql;
843
+ /**
844
+ * whereDate(), whereTime(), whereDay(), whereMonth() and whereYear() per driver, as Laravel 12's grammars: MySQL's
845
+ * date()/time()/day()/month()/year(), Postgres' ::date, ::time and extract(), SQLite's strftime() compared as text.
846
+ */
847
+ compileWhereDate(where: Extract<Where, {
848
+ type: 'date';
849
+ }>): Sql;
850
+ /**
851
+ * whereLike() per driver, as Laravel 12's grammars: Postgres compares the column as text with ilike (like when
852
+ * case-sensitive); MySQL uses like (like binary); SQLite uses like, or glob with the pattern translated.
853
+ */
854
+ compileWhereLike(where: Extract<Where, {
855
+ type: 'like';
856
+ }>): Sql;
726
857
  compileJoin(joinClause: JoinClause): Sql;
727
858
  compileHavings(havings: readonly Having[]): Sql | undefined;
728
859
  compileLimitOffset(limit: number | undefined, offset: number | undefined): Sql | undefined;
@@ -770,6 +901,13 @@ type Where = {
770
901
  values: readonly [unknown, unknown];
771
902
  not: boolean;
772
903
  boolean: WhereBoolean;
904
+ } | {
905
+ type: 'like';
906
+ column: ColumnRef;
907
+ value: string;
908
+ caseSensitive: boolean;
909
+ not: boolean;
910
+ boolean: WhereBoolean;
773
911
  } | {
774
912
  type: 'column';
775
913
  first: ColumnRef;
@@ -791,7 +929,20 @@ type Where = {
791
929
  sql: string;
792
930
  bindings: readonly unknown[];
793
931
  boolean: WhereBoolean;
932
+ } | {
933
+ type: 'date';
934
+ part: DatePart;
935
+ column: ColumnRef;
936
+ operator: string;
937
+ value: unknown;
938
+ boolean: WhereBoolean;
794
939
  };
940
+ /** The part of a date or time column a date where clause compares (whereDate() → 'date', whereYear() → 'year', …). */
941
+ type DatePart = 'date' | 'time' | 'day' | 'month' | 'year';
942
+ /** What a date where clause compares with: a Date (read in UTC), a string, a number, or DB.raw(). */
943
+ type DateWhereValue = Date | string | number | Expression;
944
+ /** whereDate('published_at', '2026-01-05') or whereDate('published_at', '>=', new Date()). */
945
+ type DateWhereArgs = [value: DateWhereValue] | [operator: string, value: DateWhereValue];
795
946
  type Having = {
796
947
  column: ColumnRef;
797
948
  operator: string;
@@ -807,11 +958,15 @@ type Order = {
807
958
  } | {
808
959
  raw: Expression;
809
960
  };
961
+ /** A column, an expression, or `(subquery) as alias` (`exists (subquery) as alias` with exists). */
810
962
  type SelectColumn = ColumnRef | {
811
963
  query: Builder$1<unknown>;
812
964
  as: string;
965
+ exists?: boolean;
813
966
  };
814
967
  type NestedCallback<Q> = (query: Q) => unknown;
968
+ /** The value when()'s callback receives: the condition's type without its falsy members. */
969
+ type Truthy<V> = Exclude<V, false | 0 | 0n | '' | null | undefined>;
815
970
  /** The key a selected column comes back under: 'users.name' → 'name', 'name as n' → 'n'. */
816
971
  declare function columnKey(column: string): string;
817
972
  /**
@@ -862,6 +1017,31 @@ declare class Builder$1<T = Row> implements QueryBuilder<T> {
862
1017
  whereBetween(column: ColumnRef, values: readonly [unknown, unknown]): this;
863
1018
  orWhereBetween(column: ColumnRef, values: readonly [unknown, unknown]): this;
864
1019
  whereNotBetween(column: ColumnRef, values: readonly [unknown, unknown]): this;
1020
+ /** Compares the date part of a column: whereDate('published_at', '2026-01-05'), whereDate('published_at', '<', new Date()). */
1021
+ whereDate(column: ColumnRef, ...args: DateWhereArgs): this;
1022
+ orWhereDate(column: ColumnRef, ...args: DateWhereArgs): this;
1023
+ /** Compares the time of day: whereTime('published_at', '>=', '09:00:00'). */
1024
+ whereTime(column: ColumnRef, ...args: DateWhereArgs): this;
1025
+ orWhereTime(column: ColumnRef, ...args: DateWhereArgs): this;
1026
+ /** Compares the day of the month: whereDay('published_at', 5). */
1027
+ whereDay(column: ColumnRef, ...args: DateWhereArgs): this;
1028
+ orWhereDay(column: ColumnRef, ...args: DateWhereArgs): this;
1029
+ /** Compares the month: whereMonth('published_at', 12). */
1030
+ whereMonth(column: ColumnRef, ...args: DateWhereArgs): this;
1031
+ orWhereMonth(column: ColumnRef, ...args: DateWhereArgs): this;
1032
+ /** Compares the year: whereYear('published_at', '>=', 2026). */
1033
+ whereYear(column: ColumnRef, ...args: DateWhereArgs): this;
1034
+ orWhereYear(column: ColumnRef, ...args: DateWhereArgs): this;
1035
+ /**
1036
+ * Laravel's whereLike(): the value is the pattern, `%` and `_` included (`whereLike('title', `%${term}%`)`).
1037
+ * Case-insensitive unless caseSensitive: ilike on Postgres, like on MySQL and SQLite (their like already ignores
1038
+ * case: MySQL through the column's collation, SQLite for ASCII letters). Case-sensitive is like on Postgres,
1039
+ * like binary on MySQL and glob on SQLite.
1040
+ */
1041
+ whereLike(column: ColumnRef, value: string, caseSensitive?: boolean, boolean?: WhereBoolean, not?: boolean): this;
1042
+ orWhereLike(column: ColumnRef, value: string, caseSensitive?: boolean): this;
1043
+ whereNotLike(column: ColumnRef, value: string, caseSensitive?: boolean, boolean?: WhereBoolean): this;
1044
+ orWhereNotLike(column: ColumnRef, value: string, caseSensitive?: boolean): this;
865
1045
  /** Compares two columns: whereColumn('updated_at', '>', 'created_at'). */
866
1046
  whereColumn(first: ColumnRef, operatorOrSecond: string, second?: ColumnRef, boolean?: WhereBoolean): this;
867
1047
  orWhereColumn(first: ColumnRef, operatorOrSecond: string, second?: ColumnRef): this;
@@ -896,10 +1076,24 @@ declare class Builder$1<T = Row> implements QueryBuilder<T> {
896
1076
  forPage(page: number, perPage?: number): this;
897
1077
  lockForUpdate(): this;
898
1078
  sharedLock(): this;
899
- /** Calls callback(this, value) when value is truthy (or the default callback otherwise). */
900
- when<V>(value: V, callback: (query: this, value: V) => unknown, otherwise?: (query: this, value: V) => unknown): this;
1079
+ /**
1080
+ * Laravel's when(): callback(query, value) runs when the value is truthy, otherwise(query, value) when it is falsy.
1081
+ * A function value is called with the query first and its result is the value. Truthiness is JavaScript's, so `'0'`
1082
+ * and `[]` are truthy: a `?active=0` filter applies, where Laravel would skip it. Returns the query; what the
1083
+ * callbacks return is ignored.
1084
+ *
1085
+ * @example
1086
+ * Post.query().when(request.query('q'), (query, q) => query.whereLike('title', `%${q}%`))
1087
+ */
1088
+ when<V>(value: (query: this) => V, callback: (query: this, value: Truthy<V>) => unknown, otherwise?: (query: this, value: V) => unknown): this;
1089
+ when<V>(value: V, callback: (query: this, value: Truthy<V>) => unknown, otherwise?: (query: this, value: V) => unknown): this;
1090
+ /** Laravel's unless(): when() with the condition reversed. callback(query, value) runs when the value is falsy. */
1091
+ unless<V>(value: (query: this) => V, callback: (query: this, value: V) => unknown, otherwise?: (query: this, value: Truthy<V>) => unknown): this;
1092
+ unless<V>(value: V, callback: (query: this, value: V) => unknown, otherwise?: (query: this, value: Truthy<V>) => unknown): this;
901
1093
  tap(callback: (query: this) => unknown): this;
902
1094
  get(): Promise<Collection<T>>;
1095
+ /** The collection get() and chunk() hand out (Eloquent's builder makes the model's collection). */
1096
+ protected newCollection(items: T[]): Collection<T>;
903
1097
  /** The raw rows, without a Collection around them. */
904
1098
  runSelect(): Promise<T[]>;
905
1099
  first(): Promise<T | undefined>;
@@ -980,6 +1174,8 @@ declare class Builder$1<T = Row> implements QueryBuilder<T> {
980
1174
  private subQuery;
981
1175
  private addNested;
982
1176
  private addWhere;
1177
+ /** Laravel's addDateBasedWhere(): one value means '='; the operator is checked against the whitelist. */
1178
+ private addDateBasedWhere;
983
1179
  private pushNull;
984
1180
  }
985
1181
  type JoinType = 'inner' | 'left' | 'right' | 'cross';
@@ -1087,6 +1283,106 @@ declare const SchemaBuilderToken: Token<SchemaBuilder>;
1087
1283
  /** The Schema facade: Schema.create('posts', (t) => { … }), Schema.table(…), Schema.dropIfExists(…). */
1088
1284
  declare const Schema: _orieljs_support.Facade<SchemaBuilder, object>;
1089
1285
 
1286
+ /**
1287
+ * A custom cast (Laravel's CastsAttributes): get() turns the stored value into what the model exposes, set() turns
1288
+ * an assigned value back into what is stored.
1289
+ */
1290
+ interface CastsAttributes<TGet = unknown, TSet = TGet> {
1291
+ get(model: object, key: string, value: unknown, attributes: Row): TGet;
1292
+ set(model: object, key: string, value: TSet, attributes: Row): unknown;
1293
+ }
1294
+ /** A TypeScript enum object (string or numeric) used as a cast: casts = { status: PostStatus }. */
1295
+ type EnumLike = Record<string, string | number>;
1296
+ type BuiltInCast = 'int' | 'integer' | 'float' | 'double' | 'real' | 'string' | 'bool' | 'boolean' | 'array' | 'json' | 'object' | 'collection' | 'date' | 'datetime' | 'immutable_date' | 'immutable_datetime' | 'timestamp' | 'hashed' | `decimal:${number}`;
1297
+ type CastDefinition = BuiltInCast | EnumLike | CastsAttributes | (new () => CastsAttributes);
1298
+ /** The values of a TypeScript enum. Numeric enums also map values back to names; those reverse entries are skipped. */
1299
+ declare function enumValues(cast: EnumLike): Array<string | number>;
1300
+ declare const isJsonCast: (cast: CastDefinition | undefined) => boolean;
1301
+ declare const isDateCast: (cast: CastDefinition | undefined) => boolean;
1302
+ /** Laravel's castAttribute(): the stored value → the value the model exposes. null stays null (except custom casts). */
1303
+ declare function castGet(model: object, key: string, cast: CastDefinition, value: unknown, attributes: Row, className: string): unknown;
1304
+ /** The value assigned to a cast attribute → the value stored in the model's attributes (and later bound). */
1305
+ declare function castSet(model: object, key: string, cast: CastDefinition, value: unknown, attributes: Row, className: string): unknown;
1306
+ /**
1307
+ * Laravel's originalIsEquivalent(): does the stored value still mean the same thing as the original?
1308
+ * Keeps save() from writing columns whose value only changed representation (1 vs true, '5' vs 5, same instant).
1309
+ */
1310
+ declare function isEquivalent(cast: CastDefinition | undefined, current: unknown, original: unknown, model: object, key: string, className: string): boolean;
1311
+
1312
+ /**
1313
+ * Laravel's Eloquent collection: what every query, relation and eager load of models returns. It is a support
1314
+ * Collection (methods that keep the items keep this class; map() and the other type-changing methods return a plain
1315
+ * Collection) with the model-aware methods: find() by key, load() and loadCount() for every model at once, fresh(),
1316
+ * modelKeys(), toQuery(), and diff()/intersect()/unique()/only()/except()/merge() that compare models by key.
1317
+ */
1318
+ declare class EloquentCollection<M extends Model = Model> extends Collection<M> {
1319
+ /** The model with this key (or this model's key), else the default; with several keys, those models. */
1320
+ find(key: readonly unknown[] | Collection<unknown>): this;
1321
+ find(key: unknown): M | undefined;
1322
+ find<D>(key: unknown, defaultValue: D): M | D;
1323
+ /** find(), or ModelNotFoundError naming the missing keys. */
1324
+ findOrFail(keys: readonly unknown[] | Collection<unknown>): this;
1325
+ findOrFail(key: unknown): M;
1326
+ /** The primary keys, in order. */
1327
+ modelKeys(): unknown[];
1328
+ /** The models keyed by their primary key (as text). */
1329
+ getDictionary(items?: Iterable<M>): Record<string, M>;
1330
+ /** The same models in a plain Collection. */
1331
+ toBase(): Collection<M>;
1332
+ /** Whether a model with this key (or this model) is in the collection; the other forms are Collection's. */
1333
+ contains(key: keyof M & string, value: unknown): boolean;
1334
+ contains(key: (keyof M & string) | ((item: M) => unknown), operator: Operator$1, value: unknown): boolean;
1335
+ contains(callback: (item: M) => boolean): boolean;
1336
+ contains(value: unknown): boolean;
1337
+ /** Collection's containsStrict(): a model matches only itself (no key matching). */
1338
+ containsStrict(key: keyof M & string, value: unknown): boolean;
1339
+ containsStrict(callback: (item: M) => boolean): boolean;
1340
+ containsStrict(value: unknown): boolean;
1341
+ /** Collection's doesntContainStrict(): a model matches only itself (no key matching). */
1342
+ doesntContainStrict(key: keyof M & string, value: unknown): boolean;
1343
+ doesntContainStrict(callback: (item: M) => boolean): boolean;
1344
+ doesntContainStrict(value: unknown): boolean;
1345
+ /** Eager loads relations onto every model, one query per relation: await posts.load('author', 'comments.author'). */
1346
+ load(...relations: EagerLoadSpec[]): Promise<this>;
1347
+ /** Loads only the relations that aren't loaded yet; nested paths are followed into the loaded relations. */
1348
+ loadMissing(...relations: string[]): Promise<this>;
1349
+ /** Adds <relation>_count attributes to every model with one query: await posts.loadCount('comments'). */
1350
+ loadCount(...relations: EagerLoadSpec[]): Promise<this>;
1351
+ /**
1352
+ * Laravel's loadAggregate(): withAggregate() for models already loaded, with one query for the whole collection.
1353
+ * The values become clean attributes (with their casts: loadExists() gives booleans).
1354
+ */
1355
+ loadAggregate(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression, fn?: string): Promise<this>;
1356
+ /** Adds <relation>_sum_<column> to every model: await users.loadSum('orders', 'price'). */
1357
+ loadSum(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this>;
1358
+ loadAvg(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this>;
1359
+ loadMin(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this>;
1360
+ loadMax(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this>;
1361
+ /** Adds a boolean <relation>_exists to every model. */
1362
+ loadExists(...relations: EagerLoadSpec[]): Promise<this>;
1363
+ /** The models as they are in the database now (without global scopes), with relations loaded; deleted ones drop out. */
1364
+ fresh(...relations: EagerLoadSpec[]): Promise<this>;
1365
+ /** The models whose keys aren't in the given models. */
1366
+ diff(items: Iterable<M>): this;
1367
+ /** The models whose keys are also in the given models. */
1368
+ intersect(items: Iterable<M>): this;
1369
+ /** One model per key (the last instance, at the first one's place); with a key or callback, Collection's unique(). */
1370
+ unique(key?: (keyof M & string) | ((item: M) => unknown)): this;
1371
+ /** The models with these keys, in the collection's order. */
1372
+ only(...keys: unknown[]): this;
1373
+ /** The models without these keys, in the collection's order. */
1374
+ except(...keys: unknown[]): this;
1375
+ /** Adds the given models, replacing the ones with the same key. */
1376
+ merge(items: Iterable<M>): this;
1377
+ makeHidden(...attributes: Array<string | string[]>): this;
1378
+ makeVisible(...attributes: Array<string | string[]>): this;
1379
+ setVisible(visible: string[]): this;
1380
+ setHidden(hidden: string[]): this;
1381
+ append(...attributes: Array<string | string[]>): this;
1382
+ /** A query of exactly these models (where key in …), for mass updates: await posts.toQuery().update({ … }). */
1383
+ toQuery(): Builder<M>;
1384
+ }
1385
+
1090
1386
  /**
1091
1387
  * A relation is the related model's query builder, constrained to the parent: post.comments() is a
1092
1388
  * Builder<Comment> with `where comments.post_id = ?`, so every builder method (where, orderBy, paginate, a local
@@ -1188,6 +1484,8 @@ declare class Builder<M extends Model = Model> extends Builder$1<M> {
1188
1484
  protected scopes: Map<string, GlobalScope>;
1189
1485
  protected removedScopes: string[];
1190
1486
  protected eagerLoad: Map<string, RelationConstraint | undefined>;
1487
+ /** Casts for the selected columns (withCasts()), merged into every model this query hydrates. */
1488
+ protected selectCasts: Record<string, CastDefinition>;
1191
1489
  constructor(model: M);
1192
1490
  getModel(): M;
1193
1491
  /** The model class's static scope<Name> method for a builder method name, if any. */
@@ -1218,6 +1516,20 @@ declare class Builder<M extends Model = Model> extends Builder$1<M> {
1218
1516
  whereNull(columns: Column<M> | Expression | Array<Column<M> | Expression>): this;
1219
1517
  whereNotNull(columns: Column<M> | Expression | Array<Column<M> | Expression>): this;
1220
1518
  whereBetween(column: Column<M> | Expression, values: readonly [unknown, unknown]): this;
1519
+ whereDate(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1520
+ orWhereDate(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1521
+ whereTime(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1522
+ orWhereTime(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1523
+ whereDay(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1524
+ orWhereDay(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1525
+ whereMonth(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1526
+ orWhereMonth(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1527
+ whereYear(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1528
+ orWhereYear(column: Column<M> | Expression, ...args: DateWhereArgs): this;
1529
+ whereLike(column: Column<M> | Expression, value: string, caseSensitive?: boolean, boolean?: WhereBoolean, not?: boolean): this;
1530
+ orWhereLike(column: Column<M> | Expression, value: string, caseSensitive?: boolean): this;
1531
+ whereNotLike(column: Column<M> | Expression, value: string, caseSensitive?: boolean, boolean?: WhereBoolean): this;
1532
+ orWhereNotLike(column: Column<M> | Expression, value: string, caseSensitive?: boolean): this;
1221
1533
  orderBy(column: Column<M> | Expression, direction?: Direction | Uppercase<Direction>): this;
1222
1534
  /** Newest first by the model's created_at column (or the given one). */
1223
1535
  latest(column?: Column<M> | Expression): this;
@@ -1226,6 +1538,12 @@ declare class Builder<M extends Model = Model> extends Builder$1<M> {
1226
1538
  /** where key = id (or key in ids). */
1227
1539
  whereKey(id: unknown): this;
1228
1540
  whereKeyNot(id: unknown): this;
1541
+ /** The models, in the model's collection (an EloquentCollection). */
1542
+ get(): Promise<EloquentCollection<M>>;
1543
+ protected newCollection(models: M[]): EloquentCollection<M>;
1544
+ /** chunk() with each chunk in the model's collection. */
1545
+ chunk(count: number, callback: (models: EloquentCollection<M>, page: number) => unknown): Promise<boolean>;
1546
+ chunkById(count: number, callback: (models: EloquentCollection<M>, page: number) => unknown, column?: string, alias?: string): Promise<boolean>;
1229
1547
  /** Runs the query, hydrates models, fires their retrieved events and eager loads the with() relations. */
1230
1548
  runSelect(): Promise<M[]>;
1231
1549
  /**
@@ -1248,6 +1566,25 @@ declare class Builder<M extends Model = Model> extends Builder$1<M> {
1248
1566
  * withCount('comments as approved_count'). Global scopes of the related model (soft deletes) apply.
1249
1567
  */
1250
1568
  withCount(...relations: EagerLoadSpec[]): this;
1569
+ /** Adds `<relation>_sum_<column>`: withSum('orders', 'price'), withSum({ 'orders as paid': (q) => … }, 'price'). */
1570
+ withSum(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): this;
1571
+ /** Adds `<relation>_avg_<column>`. */
1572
+ withAvg(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): this;
1573
+ /** Adds `<relation>_min_<column>`. */
1574
+ withMin(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): this;
1575
+ /** Adds `<relation>_max_<column>`. */
1576
+ withMax(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): this;
1577
+ /** Adds a boolean `<relation>_exists`: withExists('comments'). */
1578
+ withExists(...relations: EagerLoadSpec[]): this;
1579
+ /**
1580
+ * Laravel's withAggregate(): a correlated subquery per relation, `select <fn>(<related column>) … as <alias>`, the
1581
+ * alias being `<relation>_<fn>_<column>` unless the relation is named `'orders as alias'`. The relation's
1582
+ * constraint and the related model's global scopes apply; orderings are dropped. 'exists' selects
1583
+ * `exists (…)`, cast to a boolean. Without a function the column's first value is selected.
1584
+ */
1585
+ withAggregate(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression, fn?: string): this;
1586
+ /** Casts for selected columns, as if the model declared them: withCasts({ orders_sum_price: 'float' }). */
1587
+ withCasts(casts: Readonly<Record<string, CastDefinition>>): this;
1251
1588
  /**
1252
1589
  * Rows that have related rows: has('comments'), has('comments', '>=', 3), has('comments.author').
1253
1590
  * Uses `exists (…)` for the common "at least one"/"none" cases and a count subquery otherwise.
@@ -1270,10 +1607,13 @@ declare class Builder<M extends Model = Model> extends Builder$1<M> {
1270
1607
  exists(): Promise<boolean>;
1271
1608
  /** The column's values, through the model's casts and accessors. */
1272
1609
  pluck<V = unknown>(column: Column<M>): Promise<Collection<V>>;
1610
+ /** Whether `id` can't be one of the model's unique ids (not a UUID for HasUuids): it matches no row. */
1611
+ protected isMalformedKey(id: unknown): boolean;
1612
+ /** A malformed unique id (HasUuids, HasUlids) finds nothing without a query, as route model binding does. */
1273
1613
  find(id: unknown): Promise<M | undefined>;
1274
- findMany(ids: readonly unknown[]): Promise<Collection<M>>;
1614
+ findMany(ids: readonly unknown[]): Promise<EloquentCollection<M>>;
1275
1615
  /** find(), or ModelNotFoundError (a 404). With an array, every id must exist. */
1276
- findOrFail(ids: readonly unknown[]): Promise<Collection<M>>;
1616
+ findOrFail(ids: readonly unknown[]): Promise<EloquentCollection<M>>;
1277
1617
  findOrFail(id: unknown): Promise<M>;
1278
1618
  findOr<R>(id: unknown, callback: () => R | Promise<R>): Promise<M | R>;
1279
1619
  firstOrFail(): Promise<M>;
@@ -1319,32 +1659,6 @@ declare class Builder<M extends Model = Model> extends Builder$1<M> {
1319
1659
  protected defaultPerPage(): number;
1320
1660
  }
1321
1661
 
1322
- /**
1323
- * A custom cast (Laravel's CastsAttributes): get() turns the stored value into what the model exposes, set() turns
1324
- * an assigned value back into what is stored.
1325
- */
1326
- interface CastsAttributes<TGet = unknown, TSet = TGet> {
1327
- get(model: object, key: string, value: unknown, attributes: Row): TGet;
1328
- set(model: object, key: string, value: TSet, attributes: Row): unknown;
1329
- }
1330
- /** A TypeScript enum object (string or numeric) used as a cast: casts = { status: PostStatus }. */
1331
- type EnumLike = Record<string, string | number>;
1332
- type BuiltInCast = 'int' | 'integer' | 'float' | 'double' | 'real' | 'string' | 'bool' | 'boolean' | 'array' | 'json' | 'object' | 'collection' | 'date' | 'datetime' | 'immutable_date' | 'immutable_datetime' | 'timestamp' | `decimal:${number}`;
1333
- type CastDefinition = BuiltInCast | EnumLike | CastsAttributes | (new () => CastsAttributes);
1334
- /** The values of a TypeScript enum. Numeric enums also map values back to names; those reverse entries are skipped. */
1335
- declare function enumValues(cast: EnumLike): Array<string | number>;
1336
- declare const isJsonCast: (cast: CastDefinition | undefined) => boolean;
1337
- declare const isDateCast: (cast: CastDefinition | undefined) => boolean;
1338
- /** Laravel's castAttribute(): the stored value → the value the model exposes. null stays null (except custom casts). */
1339
- declare function castGet(model: object, key: string, cast: CastDefinition, value: unknown, attributes: Row, className: string): unknown;
1340
- /** The value assigned to a cast attribute → the value stored in the model's attributes (and later bound). */
1341
- declare function castSet(model: object, key: string, cast: CastDefinition, value: unknown, attributes: Row, className: string): unknown;
1342
- /**
1343
- * Laravel's originalIsEquivalent(): does the stored value still mean the same thing as the original?
1344
- * Keeps save() from writing columns whose value only changed representation (1 vs true, '5' vs 5, same instant).
1345
- */
1346
- declare function isEquivalent(cast: CastDefinition | undefined, current: unknown, original: unknown, model: object, key: string, className: string): boolean;
1347
-
1348
1662
  declare const MANY: unique symbol;
1349
1663
  /** Type-level marker set by count(): make()/create() then return a Collection. */
1350
1664
  interface Many {
@@ -1361,13 +1675,33 @@ interface StateContext {
1361
1675
  }
1362
1676
  type State = Row | ((attributes: Row, context: StateContext) => Row);
1363
1677
  type AnyFactory = Factory<any>;
1678
+ /**
1679
+ * What has() and for() need from a factory: its model, create(), createOne() and state(). A factory of any model,
1680
+ * counted or not, has them; Factory<any> itself would refuse a counted one, whose make(), create() and raw() return
1681
+ * lists.
1682
+ */
1683
+ interface RelatedFactory {
1684
+ readonly model: new () => Model;
1685
+ create(attributes?: Row): Promise<unknown>;
1686
+ createOne(attributes?: Row): Promise<Model>;
1687
+ state(state: State): RelatedFactory;
1688
+ }
1689
+ /**
1690
+ * A model's factory() typed as its own factory class (Laravel's `@use HasFactory<UserFactory>`): declare it in the
1691
+ * model, `declare static factory: HasFactory<UserFactory>` (with `import type`), and User.factory().unverified()
1692
+ * type-checks. The factory is still found at run time by name (database/factories/UserFactory.ts).
1693
+ */
1694
+ type HasFactory<F> = {
1695
+ (): F;
1696
+ (count: number, state?: State): F & Many;
1697
+ } & (typeof Model)['factory'];
1364
1698
  interface HasRelationship {
1365
- factory: AnyFactory;
1699
+ factory: RelatedFactory;
1366
1700
  relationship: string;
1367
1701
  pivot: Row;
1368
1702
  }
1369
1703
  interface ForRelationship {
1370
- parent: AnyFactory | Model;
1704
+ parent: RelatedFactory | Model;
1371
1705
  relationship: string;
1372
1706
  resolved?: Model;
1373
1707
  }
@@ -1413,9 +1747,9 @@ declare abstract class Factory<M extends Model = Model> {
1413
1747
  /** deleted_at = now, for soft-deleting models. */
1414
1748
  trashed(): this;
1415
1749
  /** Creates related models for each created model: has(Post.factory().count(3)) (relationship default: 'posts'). */
1416
- has(factory: AnyFactory, relationship?: string, pivot?: Row): this;
1750
+ has(factory: RelatedFactory, relationship?: string, pivot?: Row): this;
1417
1751
  /** Sets a belongsTo parent: for(User.factory()) or for(user) (relationship default: 'user'). Created once. */
1418
- for(parent: AnyFactory | Model, relationship?: string): this;
1752
+ for(parent: RelatedFactory | Model, relationship?: string): this;
1419
1753
  afterMaking(callback: (model: M) => unknown): this;
1420
1754
  afterCreating(callback: (model: M) => unknown): this;
1421
1755
  /** The attributes only, without a model (a Row, or a Row[] after count()). */
@@ -1487,7 +1821,7 @@ interface SyncChanges {
1487
1821
  * Many-to-many through a pivot table: post.tags() → belongsToMany(Tag) over post_tag (post_id, tag_id).
1488
1822
  * Each related model carries its pivot row as `tag.pivot` (withPivot() adds columns, withTimestamps() the timestamps).
1489
1823
  */
1490
- declare class BelongsToMany<R extends Model, P extends Model = Model> extends Relation<R, P, Collection<R>> {
1824
+ declare class BelongsToMany<R extends Model, P extends Model = Model> extends Relation<R, P, EloquentCollection<R>> {
1491
1825
  readonly table: string;
1492
1826
  readonly foreignPivotKey: string;
1493
1827
  readonly relatedPivotKey: string;
@@ -1511,7 +1845,7 @@ declare class BelongsToMany<R extends Model, P extends Model = Model> extends Re
1511
1845
  wherePivotIn(column: string, values: readonly unknown[]): this;
1512
1846
  /** Selects the related columns plus the pivot columns (as pivot_*), then moves those onto each model's pivot. */
1513
1847
  runSelect(): Promise<R[]>;
1514
- getResults(): Promise<Collection<R>>;
1848
+ getResults(): Promise<EloquentCollection<R>>;
1515
1849
  initRelation(models: P[], relation: string): P[];
1516
1850
  match(models: P[], results: R[], relation: string): P[];
1517
1851
  getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns?: ColumnRef[]): Builder<R>;
@@ -1560,6 +1894,8 @@ declare abstract class HasOneOrMany<R extends Model, P extends Model, Result> ex
1560
1894
  readonly foreignKey: string;
1561
1895
  readonly localKey: string;
1562
1896
  readonly morph?: MorphConstraint | undefined;
1897
+ /** The relation on each related model that chaperone() points back at the parent. */
1898
+ protected inverseRelationship: string | undefined;
1563
1899
  /**
1564
1900
  * @param foreignKey the qualified foreign key on the related table ('comments.post_id')
1565
1901
  * @param localKey the key on the parent it points at ('id')
@@ -1575,6 +1911,26 @@ declare abstract class HasOneOrMany<R extends Model, P extends Model, Result> ex
1575
1911
  getMorphType(): string | undefined;
1576
1912
  /** The parent's value in the type column, for a morph relation. */
1577
1913
  getMorphClass(): string | undefined;
1914
+ /**
1915
+ * Laravel's chaperone(): every related model this relation loads, eagerly or lazily, or makes, gets the parent as
1916
+ * its `relation` (guessed when not given: post_id → post, the parent's class, owner), so reading it needs no query:
1917
+ * `comments() { return this.hasMany(Comment).chaperone() }`.
1918
+ */
1919
+ chaperone(relation?: string): this;
1920
+ /** Laravel's inverse(): chaperone() under its other name. */
1921
+ inverse(relation?: string): this;
1922
+ withoutChaperone(): this;
1923
+ withoutInverse(): this;
1924
+ getInverseRelationship(): string | undefined;
1925
+ /** The first of the possible names that is a relation of the related model. */
1926
+ protected guessInverseRelation(): string | undefined;
1927
+ /** Laravel's candidates: the morph name, the foreign key without the parent's key, the parent's class, owner, parent. */
1928
+ protected getPossibleInverseRelations(): string[];
1929
+ /** Sets the parent on a related model, when chaperone() named the relation. */
1930
+ protected applyInverseRelationToModel<M extends R | null | undefined>(model: M, parent?: P): M;
1931
+ protected applyInverseRelationToMany(models: R[], parent?: P): R[];
1932
+ /** The relation query's rows (get(), first(), paginate(), …), pointing back at the parent with chaperone(). */
1933
+ runSelect(): Promise<R[]>;
1578
1934
  addConstraints(): void;
1579
1935
  addEagerConstraints(models: P[]): void;
1580
1936
  /** Related models grouped by their foreign key, as strings: bigint and integer keys compare equal. */
@@ -1590,8 +1946,8 @@ declare abstract class HasOneOrMany<R extends Model, P extends Model, Result> ex
1590
1946
  }
1591
1947
 
1592
1948
  /** post.comments(): many related rows hold the parent's key. */
1593
- declare class HasMany<R extends Model, P extends Model = Model> extends HasOneOrMany<R, P, Collection<R>> {
1594
- getResults(): Promise<Collection<R>>;
1949
+ declare class HasMany<R extends Model, P extends Model = Model> extends HasOneOrMany<R, P, EloquentCollection<R>> {
1950
+ getResults(): Promise<EloquentCollection<R>>;
1595
1951
  initRelation(models: P[], relation: string): P[];
1596
1952
  match(models: P[], results: R[], relation: string): P[];
1597
1953
  }
@@ -1600,7 +1956,7 @@ declare class HasMany<R extends Model, P extends Model = Model> extends HasOneOr
1600
1956
  * Related rows reached through an intermediate model: country.posts() → hasManyThrough(Post, User):
1601
1957
  * posts join users on users.id = posts.user_id where users.country_id = countries.id.
1602
1958
  */
1603
- declare class HasManyThrough<R extends Model, P extends Model = Model, T extends Model = Model> extends Relation<R, P, Collection<R>> {
1959
+ declare class HasManyThrough<R extends Model, P extends Model = Model, T extends Model = Model> extends Relation<R, P, EloquentCollection<R>> {
1604
1960
  readonly throughParent: T;
1605
1961
  readonly firstKey: string;
1606
1962
  readonly secondKey: string;
@@ -1627,8 +1983,8 @@ declare class HasManyThrough<R extends Model, P extends Model = Model, T extends
1627
1983
  addEagerConstraints(models: P[]): void;
1628
1984
  /** Selects the related columns plus the through key, then moves the key off the attributes. */
1629
1985
  runSelect(): Promise<R[]>;
1630
- getResults(): Promise<Collection<R>>;
1631
- getEager(): Promise<Collection<R>>;
1986
+ getResults(): Promise<EloquentCollection<R>>;
1987
+ getEager(): Promise<EloquentCollection<R>>;
1632
1988
  initRelation(models: P[], relation: string): P[];
1633
1989
  match(models: P[], results: R[], relation: string): P[];
1634
1990
  getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns?: ColumnRef[]): Builder<R>;
@@ -1739,6 +2095,8 @@ declare class Model implements ModelInstance {
1739
2095
  raw: unknown;
1740
2096
  value: unknown;
1741
2097
  }>;
2098
+ /** Attributes with the hashed cast that were assigned a value since the last save; save() hashes them. */
2099
+ protected pendingHashes: Set<string>;
1742
2100
  constructor();
1743
2101
  /** Runs booting()/booted() once per class, the first time the class is instantiated. */
1744
2102
  static bootIfNotBooted(): void;
@@ -1789,17 +2147,39 @@ declare class Model implements ModelInstance {
1789
2147
  * Observer classes are resolved from the container.
1790
2148
  */
1791
2149
  static observe(...observers: Array<object | (new () => object)>): void;
2150
+ /**
2151
+ * Turns the relation guard on or off: while it is on, reading a property of a relation method as if it were the
2152
+ * related model (`post.author.name`) warns once with how to read the relation. DatabaseServiceProvider turns it on
2153
+ * outside production. Turning it on again forgets which warnings were given.
2154
+ */
2155
+ static warnOnRelationPropertyAccess(enabled?: boolean): void;
2156
+ static warnsOnRelationPropertyAccess(): boolean;
1792
2157
  /** Runs fn with model events off, for this async context only. */
1793
2158
  static withoutEvents<R>(fn: () => R): R;
1794
2159
  /** A new query of this model, with its global scopes. */
1795
2160
  static query<C extends typeof Model>(this: C): ModelBuilder<C>;
1796
2161
  static where<C extends typeof Model>(this: C, ...args: WhereArgs<Instance<C>, ModelBuilder<C>>): ModelBuilder<C>;
2162
+ /** Post.when(request.query('q'), (query, q) => query.whereLike('title', `%${q}%`)): a new query, then when(). */
2163
+ static when<C extends typeof Model, V>(this: C, value: (query: ModelBuilder<C>) => V, callback: (query: ModelBuilder<C>, value: Truthy<V>) => unknown, otherwise?: (query: ModelBuilder<C>, value: V) => unknown): ModelBuilder<C>;
2164
+ static when<C extends typeof Model, V>(this: C, value: V, callback: (query: ModelBuilder<C>, value: Truthy<V>) => unknown, otherwise?: (query: ModelBuilder<C>, value: V) => unknown): ModelBuilder<C>;
2165
+ /** A new query, then unless(): the callback runs when the value is falsy. */
2166
+ static unless<C extends typeof Model, V>(this: C, value: (query: ModelBuilder<C>) => V, callback: (query: ModelBuilder<C>, value: V) => unknown, otherwise?: (query: ModelBuilder<C>, value: Truthy<V>) => unknown): ModelBuilder<C>;
2167
+ static unless<C extends typeof Model, V>(this: C, value: V, callback: (query: ModelBuilder<C>, value: V) => unknown, otherwise?: (query: ModelBuilder<C>, value: Truthy<V>) => unknown): ModelBuilder<C>;
1797
2168
  static whereKey<C extends typeof Model>(this: C, id: unknown): ModelBuilder<C>;
1798
2169
  static whereIn<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, values: readonly unknown[]): ModelBuilder<C>;
1799
2170
  static whereNotIn<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, values: readonly unknown[]): ModelBuilder<C>;
1800
2171
  static whereNull<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression): ModelBuilder<C>;
1801
2172
  static whereNotNull<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression): ModelBuilder<C>;
1802
2173
  static whereBetween<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, values: readonly [unknown, unknown]): ModelBuilder<C>;
2174
+ /** Post.whereLike('title', `%${term}%`): case-insensitive unless caseSensitive (see the query builder's whereLike()). */
2175
+ static whereLike<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, value: string, caseSensitive?: boolean): ModelBuilder<C>;
2176
+ static whereNotLike<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, value: string, caseSensitive?: boolean): ModelBuilder<C>;
2177
+ /** Post.whereDate('published_at', '2026-01-05'), Post.whereDate('published_at', '<', new Date()). */
2178
+ static whereDate<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C>;
2179
+ static whereTime<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C>;
2180
+ static whereDay<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C>;
2181
+ static whereMonth<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C>;
2182
+ static whereYear<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, ...args: DateWhereArgs): ModelBuilder<C>;
1803
2183
  static whereColumn<C extends typeof Model>(this: C, first: Column<Instance<C>>, operatorOrSecond: string, second?: Column<Instance<C>>): ModelBuilder<C>;
1804
2184
  static whereRaw<C extends typeof Model>(this: C, sql: string, bindings?: readonly unknown[]): ModelBuilder<C>;
1805
2185
  static select<C extends typeof Model>(this: C, ...columns: Array<Column<Instance<C>> | Expression>): ModelBuilder<C>;
@@ -1814,6 +2194,13 @@ declare class Model implements ModelInstance {
1814
2194
  /** Eager loads relations: Post.with('author', 'comments.user').get(). */
1815
2195
  static with<C extends typeof Model>(this: C, ...relations: EagerLoadSpec[]): ModelBuilder<C>;
1816
2196
  static withCount<C extends typeof Model>(this: C, ...relations: EagerLoadSpec[]): ModelBuilder<C>;
2197
+ /** Post.withSum('orders', 'price'): adds orders_sum_price. */
2198
+ static withSum<C extends typeof Model>(this: C, relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): ModelBuilder<C>;
2199
+ static withAvg<C extends typeof Model>(this: C, relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): ModelBuilder<C>;
2200
+ static withMin<C extends typeof Model>(this: C, relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): ModelBuilder<C>;
2201
+ static withMax<C extends typeof Model>(this: C, relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): ModelBuilder<C>;
2202
+ static withExists<C extends typeof Model>(this: C, ...relations: EagerLoadSpec[]): ModelBuilder<C>;
2203
+ static withAggregate<C extends typeof Model>(this: C, relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression, fn?: string): ModelBuilder<C>;
1817
2204
  static has<C extends typeof Model>(this: C, relation: string, operator?: string, count?: number): ModelBuilder<C>;
1818
2205
  static whereHas<C extends typeof Model>(this: C, relation: string, callback?: RelationConstraint, operator?: string, count?: number): ModelBuilder<C>;
1819
2206
  static doesntHave<C extends typeof Model>(this: C, relation: string): ModelBuilder<C>;
@@ -1823,11 +2210,11 @@ declare class Model implements ModelInstance {
1823
2210
  /** Soft deletes: only trashed rows. */
1824
2211
  static onlyTrashed<C extends typeof Model>(this: C): ModelBuilder<C>;
1825
2212
  static withoutTrashed<C extends typeof Model>(this: C): ModelBuilder<C>;
1826
- static all<C extends typeof Model>(this: C): Promise<Collection<Instance<C>>>;
2213
+ static all<C extends typeof Model>(this: C): Promise<EloquentCollection<Instance<C>>>;
1827
2214
  static find<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C> | undefined>;
1828
- static findOrFail<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<Collection<Instance<C>>>;
2215
+ static findOrFail<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<EloquentCollection<Instance<C>>>;
1829
2216
  static findOrFail<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C>>;
1830
- static findMany<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<Collection<Instance<C>>>;
2217
+ static findMany<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<EloquentCollection<Instance<C>>>;
1831
2218
  static first<C extends typeof Model>(this: C): Promise<Instance<C> | undefined>;
1832
2219
  static firstOrFail<C extends typeof Model>(this: C): Promise<Instance<C>>;
1833
2220
  static firstWhere<C extends typeof Model>(this: C, column: Column<Instance<C>> | Expression, operatorOrValue: unknown, value?: unknown): Promise<Instance<C> | undefined>;
@@ -1837,8 +2224,8 @@ declare class Model implements ModelInstance {
1837
2224
  static paginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], pageName?: string, page?: number): Promise<LengthAwarePaginator<Instance<C>>>;
1838
2225
  static simplePaginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], pageName?: string, page?: number): Promise<Paginator<Instance<C>>>;
1839
2226
  static cursorPaginate<C extends typeof Model>(this: C, perPage?: number, columns?: string[], cursorName?: string, cursor?: Cursor | string): Promise<CursorPaginator<Instance<C>>>;
1840
- static chunk<C extends typeof Model>(this: C, count: number, callback: (models: Collection<Instance<C>>, page: number) => unknown): Promise<boolean>;
1841
- static chunkById<C extends typeof Model>(this: C, count: number, callback: (models: Collection<Instance<C>>, page: number) => unknown): Promise<boolean>;
2227
+ static chunk<C extends typeof Model>(this: C, count: number, callback: (models: EloquentCollection<Instance<C>>, page: number) => unknown): Promise<boolean>;
2228
+ static chunkById<C extends typeof Model>(this: C, count: number, callback: (models: EloquentCollection<Instance<C>>, page: number) => unknown): Promise<boolean>;
1842
2229
  static each<C extends typeof Model>(this: C, callback: (model: Instance<C>, index: number) => unknown, count?: number): Promise<boolean>;
1843
2230
  static lazy<C extends typeof Model>(this: C, chunkSize?: number): LazyCollection<Instance<C>>;
1844
2231
  static lazyById<C extends typeof Model>(this: C, chunkSize?: number): LazyCollection<Instance<C>>;
@@ -1882,6 +2269,8 @@ declare class Model implements ModelInstance {
1882
2269
  hasSetMutator(key: string): boolean;
1883
2270
  /** Every cast, including the implied ones: the incrementing key (int) and the timestamp columns (datetime). */
1884
2271
  getCasts(): Record<string, CastDefinition>;
2272
+ /** Adds casts to this instance only (Laravel's mergeCasts()); withCasts() on a query does it for each result. */
2273
+ mergeCasts(casts: Readonly<Record<string, CastDefinition>>): this;
1885
2274
  hasCast(key: string, types?: string[]): boolean;
1886
2275
  /** The stored attributes, with in-place changes to json casts written back. */
1887
2276
  getAttributes(): Row;
@@ -1916,6 +2305,16 @@ declare class Model implements ModelInstance {
1916
2305
  getKeyName(): string;
1917
2306
  getKeyType(): 'int' | 'string';
1918
2307
  getIncrementing(): boolean;
2308
+ /** Whether new rows get unique string ids before `creating` (HasUuids, HasUlids). */
2309
+ usesUniqueIds(): boolean;
2310
+ /** The columns that get a unique id (HasUuids and HasUlids: the primary key). */
2311
+ uniqueIds(): string[];
2312
+ /** A new unique id (HasUuids: a version 7 UUID; HasUlids: a lower-case ULID). */
2313
+ newUniqueId(): string | undefined;
2314
+ /** Whether a value has the shape of this model's unique ids (HasUuids: a UUID). Any value passes by default. */
2315
+ isValidUniqueId(_value: unknown): boolean;
2316
+ /** Fills each empty unique id column with newUniqueId() (Laravel's setUniqueIds()). */
2317
+ setUniqueIds(): void;
1919
2318
  getKey(): unknown;
1920
2319
  getTable(): string;
1921
2320
  getConnectionName(): string | undefined;
@@ -1929,7 +2328,8 @@ declare class Model implements ModelInstance {
1929
2328
  getRouteKey(): unknown;
1930
2329
  /**
1931
2330
  * The model a route parameter value points at: where <field or route key> = value (global scopes apply, so a
1932
- * soft-deleted row isn't found). A non-numeric value for an integer primary key finds nothing without a query.
2331
+ * soft-deleted row isn't found). A non-numeric value for an integer primary key, or a value that isn't a UUID
2332
+ * (ULID) for a unique id column, finds nothing without a query.
1933
2333
  */
1934
2334
  resolveRouteBinding(value: string, field?: string): Promise<this | undefined>;
1935
2335
  /** Override to customize the binding query (Laravel's resolveRouteBindingQuery()). */
@@ -1968,6 +2368,14 @@ declare class Model implements ModelInstance {
1968
2368
  * runs no query at all. Returns false when a saving/creating/updating listener cancels.
1969
2369
  */
1970
2370
  save(): Promise<boolean>;
2371
+ /**
2372
+ * Laravel's hashed cast (castAttributeAsHashedString()), run when the model is saved because the Hasher is
2373
+ * asynchronous: each newly assigned value is hashed before the saving event, so every listener sees the hash, and
2374
+ * again just before the write (after the creating or updating event), so a value a listener assigns is hashed too.
2375
+ * A value that is already a hash is kept when it matches the configured algorithm and options, and refused
2376
+ * otherwise. Only strings and numbers are hashed (null stays null); any other value is refused.
2377
+ */
2378
+ protected hashPendingAttributes(): Promise<void>;
1971
2379
  /** Fills and saves an existing model. */
1972
2380
  update(attributes?: Row): Promise<boolean>;
1973
2381
  /**
@@ -2062,11 +2470,13 @@ declare class Model implements ModelInstance {
2062
2470
  get pivot(): Model | undefined;
2063
2471
  /** A related model instance on this model's connection when it has none of its own. */
2064
2472
  protected newRelatedInstance<C extends typeof Model>(related: C): InstanceType<C>;
2473
+ /** Whether the model has a relation method called `name` (Laravel's isRelation()). */
2474
+ isRelation(name: string): boolean;
2065
2475
  /** Calls the relation method `name` (post.comments()) and checks that it returns a relation. */
2066
2476
  getRelationInstance(name: string): Relation;
2067
2477
  /**
2068
2478
  * A loaded relation, typed from the relation method: post.getRelation('author') is User | null,
2069
- * post.getRelation('comments') is Collection<Comment>. Throws RelationNotLoadedError when it isn't loaded
2479
+ * post.getRelation('comments') is EloquentCollection<Comment>. Throws RelationNotLoadedError when it isn't loaded
2070
2480
  * (JavaScript can't lazy-load synchronously: use with(), load() or post.comments().get()).
2071
2481
  */
2072
2482
  getRelation<K extends RelationNames<this>>(name: K): RelationValue<this, K>;
@@ -2076,6 +2486,20 @@ declare class Model implements ModelInstance {
2076
2486
  loadMissing(...relations: string[]): Promise<this>;
2077
2487
  /** Loads <relation>_count attributes: await post.loadCount('comments'). */
2078
2488
  loadCount(...relations: EagerLoadSpec[]): Promise<this>;
2489
+ /** Loads an aggregate of a relation as an attribute (Laravel's loadAggregate()): see withAggregate(). */
2490
+ loadAggregate(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression, fn?: string): Promise<this>;
2491
+ /** Loads <relation>_sum_<column>: await user.loadSum('orders', 'price'). */
2492
+ loadSum(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this>;
2493
+ loadAvg(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this>;
2494
+ loadMin(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this>;
2495
+ loadMax(relations: EagerLoadSpec | EagerLoadSpec[], column: string | Expression): Promise<this>;
2496
+ /** Loads a boolean <relation>_exists. */
2497
+ loadExists(...relations: EagerLoadSpec[]): Promise<this>;
2498
+ /**
2499
+ * The collection queries of this model return (Laravel's newCollection()): an EloquentCollection. Override it to
2500
+ * return a subclass with your own methods.
2501
+ */
2502
+ newCollection<T extends Model>(this: T, models?: T[]): EloquentCollection<T>;
2079
2503
  /** Stores a loaded relation (eager loading and load() use this). */
2080
2504
  setRelation(name: string, value: unknown): this;
2081
2505
  relationLoaded(name: string): boolean;
@@ -2093,7 +2517,10 @@ declare class Model implements ModelInstance {
2093
2517
  setAppends(appends: string[]): this;
2094
2518
  /** Adds accessor-only attributes to the serialized form of this instance. */
2095
2519
  append(...attributes: Array<string | string[]>): this;
2096
- /** Attributes (through accessors and casts, dates as ISO strings), appends and loaded relations, minus hidden ones. */
2520
+ /**
2521
+ * Attributes (through accessors and casts, dates as ISO strings), appends and loaded relations, minus hidden ones.
2522
+ * A model met again while its own toArray() runs (a child chaperone() pointed back at it) gives its attributes only.
2523
+ */
2097
2524
  toArray(): Row;
2098
2525
  toJSON(): Row;
2099
2526
  attributesToArray(): Row;
@@ -2112,6 +2539,91 @@ declare class Pivot extends Model {
2112
2539
  timestamps: boolean;
2113
2540
  }
2114
2541
 
2542
+ declare const DatabaseNotification_base: typeof Model;
2543
+ /**
2544
+ * Laravel's DatabaseNotification: one row of the `notifications` table, which the database channel writes. A UUID
2545
+ * string key (HasUuids: a malformed id finds nothing without a query, so it is a 404), `data` as an array cast and
2546
+ * `read_at` as a datetime. `user.notifications()` returns these, newest first.
2547
+ */
2548
+ declare class DatabaseNotification extends DatabaseNotification_base implements DatabaseNotification$1 {
2549
+ protected table: string | undefined;
2550
+ protected keyType: 'int' | 'string';
2551
+ incrementing: boolean;
2552
+ protected guarded: string[];
2553
+ protected casts: Readonly<Record<string, CastDefinition>>;
2554
+ $attributes?: {
2555
+ id: string;
2556
+ type: string;
2557
+ notifiable_type: string;
2558
+ notifiable_id: number | string;
2559
+ data: Record<string, unknown>;
2560
+ read_at: Date | null;
2561
+ created_at: Date | null;
2562
+ updated_at: Date | null;
2563
+ };
2564
+ readonly id: string;
2565
+ readonly type: string;
2566
+ readonly notifiable_type: string;
2567
+ readonly notifiable_id: number | string;
2568
+ readonly data: Record<string, unknown>;
2569
+ read_at: Date | null;
2570
+ readonly created_at: Date | null;
2571
+ readonly updated_at: Date | null;
2572
+ /** The model the notification was sent to. */
2573
+ notifiable<R extends Model = Model>(): MorphTo<R, this>;
2574
+ /** Sets read_at to now and saves, unless it is already read. */
2575
+ markAsRead(): Promise<void>;
2576
+ /** Clears read_at and saves, unless it is already unread. */
2577
+ markAsUnread(): Promise<void>;
2578
+ read(): boolean;
2579
+ unread(): boolean;
2580
+ /** Queries of notifications return a DatabaseNotificationCollection (markAsRead() on all of them). */
2581
+ newCollection<T extends Model>(this: T, models?: T[]): EloquentCollection<T>;
2582
+ /** `query.read()`: only read notifications. */
2583
+ static scopeRead(query: Builder<DatabaseNotification>): Builder<DatabaseNotification>;
2584
+ /** `query.unread()`: only unread notifications. */
2585
+ static scopeUnread(query: Builder<DatabaseNotification>): Builder<DatabaseNotification>;
2586
+ }
2587
+ /** Laravel's DatabaseNotificationCollection: what `await user.notifications().get()` returns. */
2588
+ declare class DatabaseNotificationCollection extends EloquentCollection<DatabaseNotification> {
2589
+ /** Marks every notification as read (one save each, as in Laravel). */
2590
+ markAsRead(): Promise<void>;
2591
+ /** Marks every notification as unread. */
2592
+ markAsUnread(): Promise<void>;
2593
+ }
2594
+ /**
2595
+ * The relation `notifications()`, `readNotifications()` and `unreadNotifications()` return: a morphMany over
2596
+ * DatabaseNotification whose results (get(), the loaded relation, eager loads) are DatabaseNotificationCollections.
2597
+ * Every builder method works on it: paginate(), count(), update({ read_at }), where(), …
2598
+ */
2599
+ declare class DatabaseNotificationsRelation<P extends Model = Model> extends MorphMany<DatabaseNotification, P> {
2600
+ get(): Promise<DatabaseNotificationCollection>;
2601
+ getResults(): Promise<DatabaseNotificationCollection>;
2602
+ initRelation(models: P[], relation: string): P[];
2603
+ match(models: P[], results: DatabaseNotification[], relation: string): P[];
2604
+ }
2605
+
2606
+ type ModelConstructor = new (...args: any[]) => Model;
2607
+ /** What HasDatabaseNotifications adds to a model. */
2608
+ interface HasDatabaseNotificationsModel extends Model {
2609
+ /** The model's notifications, newest first: morphMany(DatabaseNotification, 'notifiable').latest(). */
2610
+ notifications(): DatabaseNotificationsRelation<this>;
2611
+ /** The read ones (read_at set). */
2612
+ readNotifications(): DatabaseNotificationsRelation<this>;
2613
+ /** The unread ones (read_at null). */
2614
+ unreadNotifications(): DatabaseNotificationsRelation<this>;
2615
+ }
2616
+ /**
2617
+ * Laravel's HasDatabaseNotifications: the notifications the database channel stored for this model, as queries.
2618
+ * `class User extends HasDatabaseNotifications(Model) {}`; apps get it through `Notifiable`.
2619
+ */
2620
+ declare function HasDatabaseNotifications<TBase extends ModelConstructor>(Base: TBase): TBase & (new (...args: any[]) => HasDatabaseNotificationsModel);
2621
+
2622
+ /** Laravel's HasUuids: `class Post extends HasUuids(Model) {}` keys new rows with a version 7 UUID. */
2623
+ declare function HasUuids<TBase extends ModelConstructor>(Base: TBase): TBase;
2624
+ /** Laravel's HasUlids: `class Post extends HasUlids(Model) {}` keys new rows with a lower-case ULID. */
2625
+ declare function HasUlids<TBase extends ModelConstructor>(Base: TBase): TBase;
2626
+
2115
2627
  /**
2116
2628
  * The morph map: the value stored in `*_type` columns for each model class (Laravel's Relation::morphMap()).
2117
2629
  * Without an entry the class name is stored ('Post'). Returns the current map.
@@ -2255,6 +2767,14 @@ declare class Migrator {
2255
2767
  private rollDown;
2256
2768
  /** Runs up/down on the migration's connection (made the default meanwhile), in a transaction where DDL allows it. */
2257
2769
  private runMigration;
2770
+ /**
2771
+ * SQLite's order for a migration in a transaction: foreign keys off before the transaction (SQLite ignores the pragma
2772
+ * inside one, and a table rebuild would otherwise run the ON DELETE actions of the tables that reference it), the
2773
+ * migration, a foreign key check before the commit (rows that break a key fail the migration), then foreign keys back
2774
+ * on. A migration outside a transaction runs with foreign keys as they are, so its ON DELETE and ON UPDATE actions
2775
+ * run; a table rebuild in it turns them off around itself and checks the table.
2776
+ */
2777
+ private runOnSqlite;
2258
2778
  }
2259
2779
 
2260
2780
  type SeederClass = new () => Seeder;
@@ -2429,7 +2949,11 @@ declare class RouteModelResolverImpl implements RouteModelResolver {
2429
2949
 
2430
2950
  /** Laravel 11's config/database.php defaults (the app's config/database.ts wins, key by key). */
2431
2951
  declare function databaseConfigDefaults(app: Pick<Application, 'databasePath'>): DatabaseConfig & Record<string, unknown>;
2432
- /** Points the paginators at the current request: ?page=, ?cursor=, the URL and the query string (Laravel's resolvers). */
2952
+ /**
2953
+ * Points the paginators at the current request: ?page=, ?cursor=, the URL and the query string (Laravel's resolvers).
2954
+ * A bound PaginationState is asked first for the page and the path (Livewire's WithPagination replaces Laravel's
2955
+ * resolvers the same way); what it leaves undefined comes from the request.
2956
+ */
2433
2957
  declare function usePaginationResolvers(): void;
2434
2958
  /**
2435
2959
  * Binds the database layer: the DatabaseManager (a root singleton owning the pools) behind the DB facade, the
@@ -2444,4 +2968,4 @@ declare class DatabaseServiceProvider extends ServiceProvider {
2444
2968
  private manager;
2445
2969
  }
2446
2970
 
2447
- export { AbstractPaginator, type Attributes, BelongsTo, BelongsToMany, Blueprint, type BlueprintCommand, Builder, type BuiltInCast, type BunDatabase, BunSqliteDatabase, type BunStatement, type CastDefinition, type CastsAttributes, type Column, type ColumnAttributes, ColumnDefinition, type ColumnInfo, type ColumnRef, type ColumnType, Connection, type ConnectionConfig, type CreateMigrationOptions, Cursor, CursorPaginator, type CursorPaginatorOptions, DB, type DatabaseCommandContext, type DatabaseConfig, DatabaseConfigError, DatabaseError, DatabaseManagerImpl, DatabaseServiceProvider, type Direction, type EagerLoadSpec, type EnumLike, Expression, Factory, type FactoryResult, Faker, FakerOverflowError, ForeignIdColumnDefinition, ForeignKeyDefinition, type GlobalScope, Grammar, HasMany, HasManyThrough, HasOne, HasOneOrMany, type Having, type IndexType, InvalidCastError, JoinClause, type JoinType, LengthAwarePaginator, type LoggedQuery, LogicError, MIGRATION_CREATE_STUB, MIGRATION_STUB, MIGRATION_UPDATE_STUB, MODEL_EVENTS, type Many, MassAssignmentError, Migration, MigrationCreator, type MigrationRecord, MigrationRepository, type MigrationStatus, Migrator, type MigratorOptions, Model, type ModelBuilder, type ModelClass, type ModelEvent, type ModelListener, ModelNotFoundError, ModelRegistry, type MorphConstraint, MorphMany, MorphOne, MorphTo, MySqlSchemaGrammar, OPERATORS, type Order, type PaginationLink, Paginator, type PaginatorOptions, Pivot, type PivotIds, PostgresSchemaGrammar, Builder$1 as QueryBuilder, QueryError, type RawResult, type ReferentialAction, type RegisteredModel, Relation, type RelationConstraint, type RelationNames, RelationNotFoundError, RelationNotLoadedError, type RelationValue, type RollbackOptions, RouteModelResolverImpl, Schema, SchemaBuilder, SchemaBuilderToken, SchemaGrammar, type Scope, type ScopeCallback, type ScopeStatic, type Scopes, Seeder, type SeederClass, type SelectColumn, SoftDeletingScope, SqliteSchemaGrammar, type State, type StateContext, type SyncChanges, TypeGenerator, type TypeGeneratorOptions, type Where, type WhereArgs, type WhereBoolean, buildQuery, castGet, castSet, columnKey, createDialect, databaseConfigDefaults, discoverFactories, enumValues, fake, formatDate, formatDateTime, generateModelTypes, getMorphAlias, getMorphedModel, guessTable, isBun, isDateCast, isEquivalent, isJsonCast, loadRelations, migrationDatePrefix, modelEventName, morphMap, mysqlPoolOptions, openSqlite, parseDateTime, prepareValue, raw, rawWithBindings, registerMigrationCommands, registerModelTypesCommand, resolveMorphClass, runSeeder, serializeDate, usePaginationResolvers };
2971
+ export { AbstractPaginator, type Attributes, BelongsTo, BelongsToMany, Blueprint, type BlueprintCommand, Builder, type BuiltInCast, type BunDatabase, BunSqliteDatabase, type BunStatement, type CastDefinition, type CastsAttributes, type Column, type ColumnAttributes, ColumnDefinition, type ColumnInfo, type ColumnRef, type ColumnType, Connection, type ConnectionConfig, type CreateMigrationOptions, Cursor, CursorPaginator, type CursorPaginatorOptions, DB, type DatabaseCommandContext, type DatabaseConfig, DatabaseConfigError, DatabaseError, DatabaseManagerImpl, DatabaseNotification, DatabaseNotificationCollection, DatabaseNotificationsRelation, DatabaseServiceProvider, type DatePart, type DateWhereArgs, type DateWhereValue, type Direction, type EagerLoadSpec, EloquentCollection, type EnumLike, Expression, Factory, type FactoryResult, Faker, FakerOverflowError, ForeignIdColumnDefinition, ForeignKeyDefinition, type ForeignKeyInfo, type GlobalScope, Grammar, HasDatabaseNotifications, type HasDatabaseNotificationsModel, type HasFactory, HasMany, HasManyThrough, HasOne, HasOneOrMany, HasUlids, HasUuids, type Having, type IndexInfo, type IndexType, InvalidCastError, JoinClause, type JoinType, LengthAwarePaginator, type LoggedQuery, LogicError, MIGRATION_CREATE_STUB, MIGRATION_STUB, MIGRATION_UPDATE_STUB, MODEL_EVENTS, type Many, MassAssignmentError, Migration, MigrationCreator, type MigrationRecord, MigrationRepository, type MigrationStatus, Migrator, type MigratorOptions, Model, type ModelBuilder, type ModelClass, type ModelConstructor, type ModelEvent, type ModelListener, ModelNotFoundError, ModelRegistry, type MorphConstraint, MorphMany, MorphOne, MorphTo, MySqlSchemaGrammar, OPERATORS, type Order, type PaginationLink, Paginator, type PaginatorOptions, Pivot, type PivotIds, PostgresSchemaGrammar, Builder$1 as QueryBuilder, QueryError, type RawResult, type ReferentialAction, type RegisteredModel, Relation, type RelationConstraint, type RelationNames, RelationNotFoundError, RelationNotLoadedError, type RelationValue, type RollbackOptions, RouteModelResolverImpl, Schema, SchemaBuilder, SchemaBuilderToken, SchemaGrammar, type SchemaStep, type Scope, type ScopeCallback, type ScopeStatic, type Scopes, Seeder, type SeederClass, type SelectColumn, SoftDeletingScope, SqliteSchemaGrammar, type State, type StateContext, type SyncChanges, type TableRebuild, TypeGenerator, type TypeGeneratorOptions, type Where, type WhereArgs, type WhereBoolean, buildQuery, castGet, castSet, columnKey, createDialect, databaseConfigDefaults, discoverFactories, enumValues, fake, formatDate, formatDateTime, generateModelTypes, getMorphAlias, getMorphedModel, guessTable, isBun, isDateCast, isEquivalent, isJsonCast, isTableRebuild, loadRelations, migrationDatePrefix, modelEventName, morphMap, mysqlPoolOptions, openSqlite, parseDateTime, prepareValue, raw, rawWithBindings, registerMigrationCommands, registerModelTypesCommand, resolveMorphClass, runSeeder, serializeDate, usePaginationResolvers };