Podcast
Questions and Answers
What does Eloquent primarily do in Laravel?
What does Eloquent primarily do in Laravel?
Where do Eloquent models typically reside within a Laravel application?
Where do Eloquent models typically reside within a Laravel application?
Which command is used to generate a new Eloquent model?
Which command is used to generate a new Eloquent model?
What is the purpose of the --migration or -m option when generating a model?
What is the purpose of the --migration or -m option when generating a model?
Signup and view all the answers
What naming convention does Eloquent use to determine the database table name from a model?
What naming convention does Eloquent use to determine the database table name from a model?
Signup and view all the answers
What command provides an overview of all a model's attributes and relationships?
What command provides an overview of all a model's attributes and relationships?
Signup and view all the answers
Which of the following options can be generated using the make:model command?
Which of the following options can be generated using the make:model command?
Signup and view all the answers
What characteristic does an Eloquent model NOT possess?
What characteristic does an Eloquent model NOT possess?
Signup and view all the answers
What property needs to be set to use a non-incrementing primary key in an Eloquent model?
What property needs to be set to use a non-incrementing primary key in an Eloquent model?
Signup and view all the answers
What trait should be used in a model to implement UUID as the primary key?
What trait should be used in a model to implement UUID as the primary key?
Signup and view all the answers
Which property must be defined to customize the format of model timestamps?
Which property must be defined to customize the format of model timestamps?
Signup and view all the answers
How can you prevent Eloquent from automatically managing the created_at and updated_at timestamps?
How can you prevent Eloquent from automatically managing the created_at and updated_at timestamps?
Signup and view all the answers
What is the maximum length of a UUID used as a primary key in Eloquent?
What is the maximum length of a UUID used as a primary key in Eloquent?
Signup and view all the answers
Which property should be defined to specify a different primary key column for a model?
Which property should be defined to specify a different primary key column for a model?
Signup and view all the answers
What method is used to refresh an instance of an Eloquent model retrieved from the database?
What method is used to refresh an instance of an Eloquent model retrieved from the database?
Signup and view all the answers
What must be set on a model to utilize ULIDs instead of UUIDs?
What must be set on a model to utilize ULIDs instead of UUIDs?
Signup and view all the answers
Which method can be invoked to disable lazy loading in Eloquent?
Which method can be invoked to disable lazy loading in Eloquent?
Signup and view all the answers
What is the main limitation of Eloquent regarding composite primary keys?
What is the main limitation of Eloquent regarding composite primary keys?
Signup and view all the answers
What property can be defined to specify a default database connection for a model?
What property can be defined to specify a default database connection for a model?
Signup and view all the answers
What must you define to set default values for model attributes?
What must you define to set default values for model attributes?
Signup and view all the answers
Using which method will allow operations on a model without modifying its updated_at timestamp?
Using which method will allow operations on a model without modifying its updated_at timestamp?
Signup and view all the answers
What is the main purpose of the refresh method in Eloquent?
What is the main purpose of the refresh method in Eloquent?
Signup and view all the answers
Which method is recommended for handling large numbers of Eloquent models to avoid memory issues?
Which method is recommended for handling large numbers of Eloquent models to avoid memory issues?
Signup and view all the answers
What does the cursor method do in Eloquent collections?
What does the cursor method do in Eloquent collections?
Signup and view all the answers
When should you use the chunkById method?
When should you use the chunkById method?
Signup and view all the answers
How does the lazy method differ from the chunk method?
How does the lazy method differ from the chunk method?
Signup and view all the answers
What is the purpose of the subquery functionality in Eloquent?
What is the purpose of the subquery functionality in Eloquent?
Signup and view all the answers
What will the findOr method return if no results are found?
What will the findOr method return if no results are found?
Signup and view all the answers
Which method allows you to remove models from a collection using a closure?
Which method allows you to remove models from a collection using a closure?
Signup and view all the answers
What is the best use case for the lazyById method?
What is the best use case for the lazyById method?
Signup and view all the answers
How does using chunking improve memory efficiency?
How does using chunking improve memory efficiency?
Signup and view all the answers
What does the orderBy method support in the context of Eloquent?
What does the orderBy method support in the context of Eloquent?
Signup and view all the answers
What is a limitation of the cursor method when processing large datasets?
What is a limitation of the cursor method when processing large datasets?
Signup and view all the answers
What does the find method return?
What does the find method return?
Signup and view all the answers
What property needs to be defined on an Eloquent model to start listening to model events?
What property needs to be defined on an Eloquent model to start listening to model events?
Signup and view all the answers
Which event is dispatched when an existing model is modified and the save method is called?
Which event is dispatched when an existing model is modified and the save method is called?
Signup and view all the answers
Which interface should an observer implement to have its event handlers execute only after a database transaction is committed?
Which interface should an observer implement to have its event handlers execute only after a database transaction is committed?
Signup and view all the answers
What command is used to create a new observer class in Laravel?
What command is used to create a new observer class in Laravel?
Signup and view all the answers
What method is used to temporarily mute all events fired by a model?
What method is used to temporarily mute all events fired by a model?
Signup and view all the answers
Where can observers be manually registered in an application?
Where can observers be manually registered in an application?
Signup and view all the answers
What is dispatched when a model is created or updated, regardless of attribute changes?
What is dispatched when a model is created or updated, regardless of attribute changes?
Signup and view all the answers
What method can be used to save a model without dispatching any events?
What method can be used to save a model without dispatching any events?
Signup and view all the answers
Which event type is dispatched before changes to the model are saved?
Which event type is dispatched before changes to the model are saved?
Signup and view all the answers
What is the purpose of using closures when registering model events?
What is the purpose of using closures when registering model events?
Signup and view all the answers
What method is used to insert a new record in the database when attributes are mass assignable?
What method is used to insert a new record in the database when attributes are mass assignable?
Signup and view all the answers
What does the $guarded property represent in a model?
What does the $guarded property represent in a model?
Signup and view all the answers
What would happen if an attribute is not in the $fillable array during a mass assignment?
What would happen if an attribute is not in the $fillable array during a mass assignment?
Signup and view all the answers
Which method should be invoked to handle mass assignment exceptions?
Which method should be invoked to handle mass assignment exceptions?
Signup and view all the answers
What is the purpose of Eloquent's upsert method?
What is the purpose of Eloquent's upsert method?
Signup and view all the answers
How can you delete all associated records of a model at once?
How can you delete all associated records of a model at once?
Signup and view all the answers
What happens to a model when it is soft deleted?
What happens to a model when it is soft deleted?
Signup and view all the answers
Which trait must be added to a model to enable soft deleting?
Which trait must be added to a model to enable soft deleting?
Signup and view all the answers
How do you restore a soft deleted model?
How do you restore a soft deleted model?
Signup and view all the answers
Which method will permanently delete a soft deleted model?
Which method will permanently delete a soft deleted model?
Signup and view all the answers
What does the withTrashed method do?
What does the withTrashed method do?
Signup and view all the answers
How can you retrieve only soft deleted models?
How can you retrieve only soft deleted models?
Signup and view all the answers
What trait is used to periodically delete models that are no longer needed?
What trait is used to periodically delete models that are no longer needed?
Signup and view all the answers
When marking models as Prunable, what method must be implemented?
When marking models as Prunable, what method must be implemented?
Signup and view all the answers
What is the purpose of the model:prune Artisan command?
What is the purpose of the model:prune Artisan command?
Signup and view all the answers
Which option allows you to prevent certain models from being pruned?
Which option allows you to prevent certain models from being pruned?
Signup and view all the answers
What trait must models use for mass deletion without triggering the pruning process?
What trait must models use for mass deletion without triggering the pruning process?
Signup and view all the answers
Which of the following statements is true about global scopes?
Which of the following statements is true about global scopes?
Signup and view all the answers
What method is invoked to register a new global scope to a model?
What method is invoked to register a new global scope to a model?
Signup and view all the answers
What is the function of the withoutGlobalScope method?
What is the function of the withoutGlobalScope method?
Signup and view all the answers
What happens when a model is replicated using the replicate method?
What happens when a model is replicated using the replicate method?
Signup and view all the answers
What happens when a model is not found using the findOrFail method?
What happens when a model is not found using the findOrFail method?
Signup and view all the answers
Which method can be used to define a dynamic scope that accepts parameters?
Which method can be used to define a dynamic scope that accepts parameters?
Signup and view all the answers
How can you quickly check if two models are identical?
How can you quickly check if two models are identical?
Signup and view all the answers
What is the primary purpose of the firstOrCreate method?
What is the primary purpose of the firstOrCreate method?
Signup and view all the answers
Which method would you use to ensure a model instance is returned without saving it to the database?
Which method would you use to ensure a model instance is returned without saving it to the database?
Signup and view all the answers
Which Eloquent event is dispatched when an existing model is retrieved from the database?
Which Eloquent event is dispatched when an existing model is retrieved from the database?
Signup and view all the answers
How can you update a model that already exists in the database?
How can you update a model that already exists in the database?
Signup and view all the answers
What is the purpose of local scopes in Eloquent?
What is the purpose of local scopes in Eloquent?
Signup and view all the answers
Which command would you use to generate a new global scope in Laravel?
Which command would you use to generate a new global scope in Laravel?
Signup and view all the answers
What should be specified on a model class before using the create method?
What should be specified on a model class before using the create method?
Signup and view all the answers
What does the updateOrCreate method do?
What does the updateOrCreate method do?
Signup and view all the answers
What does the higher order orWhere method help with in Eloquent?
What does the higher order orWhere method help with in Eloquent?
Signup and view all the answers
What does the isDirty method indicate about a model's attributes?
What does the isDirty method indicate about a model's attributes?
Signup and view all the answers
What method should be called to add custom clauses to a query when writing a global scope?
What method should be called to add custom clauses to a query when writing a global scope?
Signup and view all the answers
Which method would you use to retrieve the original attributes of a model?
Which method would you use to retrieve the original attributes of a model?
Signup and view all the answers
What is the purpose of the --pretend option in the model:prune command?
What is the purpose of the --pretend option in the model:prune command?
Signup and view all the answers
In what situation would you use the count method in Eloquent?
In what situation would you use the count method in Eloquent?
Signup and view all the answers
What happens to the model's timestamps when the save method is called?
What happens to the model's timestamps when the save method is called?
Signup and view all the answers
What is the purpose of the max method when used with Eloquent models?
What is the purpose of the max method when used with Eloquent models?
Signup and view all the answers
When would a ModelNotFoundException be thrown?
When would a ModelNotFoundException be thrown?
Signup and view all the answers
Why is mass assignment protection necessary in Eloquent models?
Why is mass assignment protection necessary in Eloquent models?
Signup and view all the answers
Study Notes
Eloquent Introduction
- Eloquent is Laravel's object-relational mapper (ORM) for interacting with databases.
- Each database table has a corresponding model used for table interactions (inserting, updating, deleting, retrieving).
Getting Started
- Models are typically located in
app/Models
and extendIlluminate\Database\Eloquent\Model
. - Use the
make:model
Artisan command to generate models. - The
--migration
or-m
option generates a migration file alongside the model. - Other classes (factories, seeders, policies, controllers, form requests) can be generated alongside the model.
- Use the
model:show
Artisan command to inspect model attributes and relationships.
Eloquent Model Conventions
- Tables are named after the plural, snake-cased version of the model name (e.g.,
Flight
model maps toflights
table). - Use
$table
property to specify a different table name for a model if it doesn't follow the convention. - Primary keys default to
id
column. Use$primaryKey
to change the primary key. - Primary keys default to auto-incrementing integers. Use
$incrementing = false
if not. - If primary key is non-numeric use
$keyType = 'string'
. - Eloquent doesn't support composite primary keys.
- You can use UUIDs (universally unique identifiers) with the
HasUuids
trait. - Specify columns for UUIDs with
uniqueIds
method. - Use ULIDs (Universally Unique Lexicographically Sortable Identifiers) with the
HasUlids
trait instead of UUIDs.
Timestamps
-
created_at
andupdated_at
columns auto-populate when models are created/updated. - Set
$timestamps = false
to disable automatic timestamp management. - Use
$dateFormat
to customize timestamp format. - Use
CREATED_AT
andUPDATED_AT
constants to customize timestamp column names. - Use
withoutTimestamps
to avoid modifyingupdated_at
for model operations within a closure. - Use appropriate methods for model interactions that require specifying a different database connection.
Default Attribute Values
- Define
$attributes
to set default values for attributes. - Values in
$attributes
should be in their raw database-storable format.
Eloquent Strictness
- Use
preventLazyLoading
inAppServiceProvider
to prevent lazy loading (useful for non-production environments). - Use
preventSilentlyDiscardingAttributes
to throw exceptions when attempting to set unfillable attributes (important for local development).
Retrieving Models
- Eloquent models act as query builders for database interaction.
- Use
all()
to retrieve all records from a table. - Use
get()
with constraints to retrieve specific records. - Use
fresh()
to re-retrieve a model from the database, not affecting the existing instance. - Use
refresh()
to re-hydrate the existing model with fresh data, refreshing loaded relationships.
Collections
- Eloquent's
all()
andget()
returnIlluminate\Database\Eloquent\Collection
. - Use collection methods (e.g.,
reject()
) on these objects. - Collections are iterable; you can loop through them like arrays.
Chunks, Lazy Collections, Cursors
- Use
chunk()
orchunkById()
to efficiently process large numbers of records in chunks. - Use
chunk()
for simpler iteration; usechunkById()
to incrementally process models by ID. - Use
lazy()
orlazyById()
to process large datasets as a lazy stream. - Use
cursor()
for maximum memory efficiency while maintaining Laravel collection functionality. Note that there's a memory limit due to PHP's PDO cache.
Advanced Subqueries
- Use subqueries in
select()
andaddSelect()
for accessing related data efficiently. - Use subqueries in
orderBy()
to sort results based on related data.
Retrieving Single Models/Aggregates
- Use
find()
,first()
,firstWhere()
for retrieving single models. - Use
findOr()
,firstOr()
for fallback values if a model isn't found. - Use
findOrFail()
,firstOrFail()
to throw exceptions when no matching model is found.
Retrieving/Creating Models
-
firstOrCreate()
finds or creates a model matching provided criteria. -
firstOrNew()
finds a model or returns a new, unsaved instance.
Inserts, Updates & Deletes
-
save()
inserts or updates a model. -
create()
inserts a new model in a single statement (must definefillable
orguarded
). -
update()
updates multiple models, expecting an array of column-value pairs, returns affected rows. -
updateOrCreate()
updates or creates a model matching given criteria. - Use
delete()
to delete a model. - Use
truncate()
to delete all records. - Use
destroy()
to delete a model by its primary key or an array of primary keys ("or" to delete multiple). -
forceDestroy()
deletes a model permanently (for soft deletes). - Delete models by building Eloquent queries.
- Use
mass-delete()
to handle model deletion efficiently in the context of queries.
Soft Delete
- Implement soft delete with
SoftDeletes
trait anddeleted_at
column. -
delete()
methods will move the record to a soft-delete state, not delete it. -
withTrashed()
include soft-deleted models in the query results; -
onlyTrashed()
retrieves only soft-deleted models; - Use
forceDelete()
to permanently remove soft-deleted models.
Pruning Models
- Implement pruning for periodically deleting unneeded models (
Prunable
orMassPrunable
trait). - Implement a
pruning
method that constructs a query for deleting models, andmodel:prune
Artisan command.
Replicating Models
-
replicate()
creates an unsaved copy of an existing model. -
replicate()
method arguments allow specifying which columns should not be replicated
Query Scopes
- Global scopes define constraints applied to all queries for a model.
- Create global scopes with
make:scope
Artisan command. - Define global scopes via closure-based syntax (anonymous global scopes).
- Local scopes are similar to global scopes but focused on specific methods for ease of use.
-
withoutGlobalScope()
,withoutGlobalScopes()
to remove scopes from a query.
Dynamic Scopes
- Create scopes that accept parameters for more flexible querying.
Comparing Models
- Use
is()
,isNot()
to compare models efficiently, checking primary keys, and table.
Events
- Eloquent models dispatch events during various lifecycle stages, allowing for custom actions.
- Listen to model events using closures, observers, or custom events.
Observers
- Use observers to handle multiple events within a single class.
- Using a observer you can control model actions efficiently for specific events during database interactions.
Muting Events
- Use
withoutEvents
to silence events temporarily within a closure, or thesaveQuietly()
method to modify operations without triggering events.
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.
Description
Test your knowledge of Eloquent, the powerful ORM in Laravel. This quiz covers key features, model generation, and naming conventions used in Eloquent. Perfect for Laravel developers looking to enhance their understanding of model management.