skip to content

Eloquent Models

Eloquent's model layer: table conventions, relations and eager loading, casts, scopes and lifecycle events. Interviewers go straight at lazy loading and N+1, which Eloquent makes effortless to cause.

on this pageshow

explore

questions

page 2 of 2

With Eloquent, what do withCount(), withSum() and withExists() add to a query, and how are the resulting attributes named?

level: middleimportance: should knowfreq 52%

basics

~20 s

They add a correlated subselect to the SELECT list, so each parent row comes back with an aggregate attribute and no related models are loaded: tags_count, purchases_sum_amount, or a boolean comments_exists. An 'as' alias renames it.

open as a page

In Eloquent, what do hasOneThrough() and hasManyThrough() declare, and which table does each of their key arguments refer to?

level: middleimportance: should knowfreq 40%

basics

~20 s

hasManyThrough() and hasOneThrough() reach models two has-type hops away through an intermediate model in one query. After the final and intermediate classes, the third argument is the key on the intermediate table and the fourth the key on the final table.

open as a page

In Laravel, how do the Prunable and MassPrunable traits with php artisan model:prune remove old Eloquent records, and how do the two differ?

level: middleimportance: should knowfreq 32%

basics

~20 s

Both traits make a model define prunable(), a query for rows to remove, and model:prune runs it. Prunable loads matches in chunks and deletes each model, calling pruning() and firing events; MassPrunable deletes by query, faster but with no events or hook.

open as a page

With Eloquent's encrypted casts, what is stored in the column, and what can you no longer do with an encrypted attribute?

level: seniorimportance: should knowfreq 30%

basics

~20 s

The column stores ciphertext from Laravel's encrypter, keyed by APP_KEY; Eloquent decrypts on read and encrypts on write. The payload is long, so use a TEXT column, and SQL can no longer filter, sort, index or join on it.

open as a page

An Eloquent model sets $guarded = [] and a controller calls Reservation::create($request->all()); why is that a mass-assignment hole, and how do you harden it?

level: seniorimportance: should knowfreq 55%

basics

~20 s

With $guarded = [] every posted key that names a column is written, so a user can add is_vip or user_id to the request. Harden it with a $fillable allow-list, explicit input arrays, server-set privileged fields and strict discarding in development.

open as a page

A nightly Eloquent job walks two million product rows and updates each one; when do you choose chunk(), chunkById(), lazy() or cursor(), and why?

level: seniorimportance: should knowfreq 55%

basics

~20 s

Use chunkById() or lazyById() when the loop updates rows it filters on, since offset-based chunk() and lazy() then skip rows. cursor() runs one query and holds one model but cannot eager load, and the driver may still buffer the result.

open as a page

For a nightly Eloquent product-feed import, why use Product::upsert() instead of updateOrCreate() per row, and what does upsert() skip?

level: seniorimportance: should knowfreq 42%

basics

~20 s

upsert() inserts or updates a whole batch in one statement, where updateOrCreate() costs a select plus a write per row. It sets timestamps but skips model events, casts, mutators and mass-assignment filtering, and needs a unique index on uniqueBy.

open as a page

In Laravel 13, what does Model::automaticallyEagerLoadRelationships() change about lazy loading, and when would you still write with() yourself?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Model::automaticallyEagerLoadRelationships() turns a lazy load on any model from a collection into one batched load for every model in that collection. It fixes plain N+1 loops, but not constrained loads, counts, relation method calls or one-by-one fetches.

open as a page

A Laravel photo site's tag editor calls $photo->tags()->sync($request->input('tags', [])); why can tags vanish or half-update, and how do you harden it?

level: seniorimportance: should knowfreq 38%

basics

~20 s

A missing tags field becomes [], and sync([]) detaches every tag. sync() also runs several statements without a transaction, so a bad ID can fail after links are deleted. Sync only when the field is present, validate IDs, use syncOrFail().

open as a page

In Eloquent, how do morphTo, morphMany and morphToMany model polymorphic relations, and why call Relation::enforceMorphMap() in production apps?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Polymorphic relations store a type and an id on the child so one model can belong to several parent types. enforceMorphMap() stores short aliases instead of class names and throws for unmapped models, so renames and new models cannot corrupt the type column.

open as a page

A Laravel legal-case app isolates law firms with an Eloquent global scope; which code paths still leak or lose matters, and how do you guard them?

level: seniorimportance: should knowfreq 36%

basics

~20 s

DB::table() and raw SQL skip the scope; a builder-level forceDelete() runs with no global scopes; a scope reading auth() finds no user in jobs and commands; and withoutGlobalScopes() calls spread. Pass firm context explicitly, fail closed without it, and test cross-firm access.

open as a page

In an Eloquent model, what does the $attributes property do, and why must its default values be written in raw database form?

level: middleimportance: nice to knowfreq 30%

basics

~20 s

The $attributes property gives new model instances default column values. They sit in the raw attributes array without passing through casts or mutators, so a JSON-cast column needs the string '[]', not a PHP array.

open as a page

With Eloquent, what problem does calling chaperone() on a hasMany relation solve, and what should you watch for when using it?

level: middleimportance: nice to knowfreq 22%

basics

~20 s

Eager-loaded children do not get their parent set, so $comment->post inside a loop over $post->comments lazy loads the post again. chaperone() sets that inverse relation on each child after the query, with no extra query.

open as a page

In Eloquent, what do latestOfMany() and ofMany() add to a hasOne relation, and why prefer them over hasMany()->latest()->first()?

level: middleimportance: nice to knowfreq 28%

basics

~20 s

latestOfMany(), oldestOfMany() and ofMany() turn a hasOne into the single latest, oldest or best row of a has-many, resolved by a grouped subquery join. Unlike latest()->first(), it is a real relation that can be eager loaded for many parents at once.

open as a page

showing 31–44 of 44