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 pageshowhide
explore
- Table Conventions & Mass Assignment5 questions
- Retrieving & Saving Records6 questions
- Relationship Types5 questions
- Querying & Syncing Relations6 questions
- Eager Loading & Strictness6 questions
- Casts, Accessors & Mutators6 questions
- Scopes & Soft Deletes5 questions
- Lifecycle Events & Observers5 questions
questions
page 2 of 2With Eloquent, what do withCount(), withSum() and withExists() add to a query, and how are the resulting attributes named?
basics
~20 sThey 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.
In Eloquent, what do hasOneThrough() and hasManyThrough() declare, and which table does each of their key arguments refer to?
basics
~20 shasManyThrough() 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.
In Laravel, how do the Prunable and MassPrunable traits with php artisan model:prune remove old Eloquent records, and how do the two differ?
basics
~20 sBoth 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.
With Eloquent's encrypted casts, what is stored in the column, and what can you no longer do with an encrypted attribute?
basics
~20 sThe 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.
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?
basics
~20 sWith $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.
A nightly Eloquent job walks two million product rows and updates each one; when do you choose chunk(), chunkById(), lazy() or cursor(), and why?
basics
~20 sUse 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.
For a nightly Eloquent product-feed import, why use Product::upsert() instead of updateOrCreate() per row, and what does upsert() skip?
basics
~20 supsert() 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.
In Laravel 13, what does Model::automaticallyEagerLoadRelationships() change about lazy loading, and when would you still write with() yourself?
basics
~20 sModel::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.
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?
basics
~20 sA 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().
In Eloquent, how do morphTo, morphMany and morphToMany model polymorphic relations, and why call Relation::enforceMorphMap() in production apps?
basics
~20 sPolymorphic 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.
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?
basics
~20 sDB::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.
In an Eloquent model, what does the $attributes property do, and why must its default values be written in raw database form?
basics
~20 sThe $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.
With Eloquent, what problem does calling chaperone() on a hasMany relation solve, and what should you watch for when using it?
basics
~20 sEager-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.
In Eloquent, what do latestOfMany() and ofMany() add to a hasOne relation, and why prefer them over hasMany()->latest()->first()?
basics
~20 slatestOfMany(), 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.
showing 31–44 of 44