Podcast
Questions and Answers
What does Eloquent primarily do in Laravel?
What does Eloquent primarily do in Laravel?
- It organizes database tables into directories.
- It helps convert database queries into HTML.
- It allows for easy interaction with the database through an ORM. (correct)
- It provides a framework for creating RESTful APIs.
Where do Eloquent models typically reside within a Laravel application?
Where do Eloquent models typically reside within a Laravel application?
- app/Models (correct)
- app/Database
- database/Models
- resources/Models
Which command is used to generate a new Eloquent model?
Which command is used to generate a new Eloquent model?
- make:model (correct)
- model:create
- generate:model
- make:class
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?
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?
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?
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?
What characteristic does an Eloquent model NOT possess?
What characteristic does an Eloquent model NOT possess?
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?
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?
Which property must be defined to customize the format of model timestamps?
Which property must be defined to customize the format of model timestamps?
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?
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?
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?
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?
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?
Which method can be invoked to disable lazy loading in Eloquent?
Which method can be invoked to disable lazy loading in Eloquent?
What is the main limitation of Eloquent regarding composite primary keys?
What is the main limitation of Eloquent regarding composite primary keys?
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?
What must you define to set default values for model attributes?
What must you define to set default values for model attributes?
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?
What is the main purpose of the refresh method in Eloquent?
What is the main purpose of the refresh method in Eloquent?
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?
What does the cursor method do in Eloquent collections?
What does the cursor method do in Eloquent collections?
When should you use the chunkById method?
When should you use the chunkById method?
How does the lazy method differ from the chunk method?
How does the lazy method differ from the chunk method?
What is the purpose of the subquery functionality in Eloquent?
What is the purpose of the subquery functionality in Eloquent?
What will the findOr method return if no results are found?
What will the findOr method return if no results are found?
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?
What is the best use case for the lazyById method?
What is the best use case for the lazyById method?
How does using chunking improve memory efficiency?
How does using chunking improve memory efficiency?
What does the orderBy method support in the context of Eloquent?
What does the orderBy method support in the context of Eloquent?
What is a limitation of the cursor method when processing large datasets?
What is a limitation of the cursor method when processing large datasets?
What does the find method return?
What does the find method return?
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?
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?
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?
What command is used to create a new observer class in Laravel?
What command is used to create a new observer class in Laravel?
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?
Where can observers be manually registered in an application?
Where can observers be manually registered in an application?
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?
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?
Which event type is dispatched before changes to the model are saved?
Which event type is dispatched before changes to the model are saved?
What is the purpose of using closures when registering model events?
What is the purpose of using closures when registering model events?
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?
What does the $guarded property represent in a model?
What does the $guarded property represent in a model?
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?
Which method should be invoked to handle mass assignment exceptions?
Which method should be invoked to handle mass assignment exceptions?
What is the purpose of Eloquent's upsert method?
What is the purpose of Eloquent's upsert method?
How can you delete all associated records of a model at once?
How can you delete all associated records of a model at once?
What happens to a model when it is soft deleted?
What happens to a model when it is soft deleted?
Which trait must be added to a model to enable soft deleting?
Which trait must be added to a model to enable soft deleting?
How do you restore a soft deleted model?
How do you restore a soft deleted model?
Which method will permanently delete a soft deleted model?
Which method will permanently delete a soft deleted model?
What does the withTrashed method do?
What does the withTrashed method do?
How can you retrieve only soft deleted models?
How can you retrieve only soft deleted models?
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?
When marking models as Prunable, what method must be implemented?
When marking models as Prunable, what method must be implemented?
What is the purpose of the model:prune Artisan command?
What is the purpose of the model:prune Artisan command?
Which option allows you to prevent certain models from being pruned?
Which option allows you to prevent certain models from being pruned?
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?
Which of the following statements is true about global scopes?
Which of the following statements is true about global scopes?
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?
What is the function of the withoutGlobalScope method?
What is the function of the withoutGlobalScope method?
What happens when a model is replicated using the replicate method?
What happens when a model is replicated using the replicate method?
What happens when a model is not found using the findOrFail method?
What happens when a model is not found using the findOrFail method?
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?
How can you quickly check if two models are identical?
How can you quickly check if two models are identical?
What is the primary purpose of the firstOrCreate method?
What is the primary purpose of the firstOrCreate method?
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?
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?
How can you update a model that already exists in the database?
How can you update a model that already exists in the database?
What is the purpose of local scopes in Eloquent?
What is the purpose of local scopes in Eloquent?
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?
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?
What does the updateOrCreate method do?
What does the updateOrCreate method do?
What does the higher order orWhere method help with in Eloquent?
What does the higher order orWhere method help with in Eloquent?
What does the isDirty method indicate about a model's attributes?
What does the isDirty method indicate about a model's attributes?
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?
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?
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?
In what situation would you use the count method in Eloquent?
In what situation would you use the count method in Eloquent?
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?
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?
When would a ModelNotFoundException be thrown?
When would a ModelNotFoundException be thrown?
Why is mass assignment protection necessary in Eloquent models?
Why is mass assignment protection necessary in Eloquent models?
Flashcards
What is Eloquent?
What is Eloquent?
Eloquent is an object-relational mapper (ORM) included in Laravel that simplifies database interactions by allowing you to interact with tables using models.
What is a Model?
What is a Model?
A Model in Eloquent represents a database table. It allows you to create, read, update, and delete records in that table.
How to generate a Model?
How to generate a Model?
You can use the 'make:model' Artisan command to generate a new Eloquent model.
Model with Migration?
Model with Migration?
Signup and view all the flashcards
What is the 'model:show' command?
What is the 'model:show' command?
Signup and view all the flashcards
Eloquent Table Naming Convention
Eloquent Table Naming Convention
Signup and view all the flashcards
Overriding Table Name
Overriding Table Name
Signup and view all the flashcards
Why use Eloquent?
Why use Eloquent?
Signup and view all the flashcards
Fresh Method
Fresh Method
Signup and view all the flashcards
Refresh Method
Refresh Method
Signup and view all the flashcards
Eloquent Collection
Eloquent Collection
Signup and view all the flashcards
Reject Method
Reject Method
Signup and view all the flashcards
Chunking Results
Chunking Results
Signup and view all the flashcards
Chunk Method
Chunk Method
Signup and view all the flashcards
ChunkById Method
ChunkById Method
Signup and view all the flashcards
Lazy Method
Lazy Method
Signup and view all the flashcards
LazyById Method
LazyById Method
Signup and view all the flashcards
Cursor Method
Cursor Method
Signup and view all the flashcards
Subquery Selects
Subquery Selects
Signup and view all the flashcards
Subquery Ordering
Subquery Ordering
Signup and view all the flashcards
Find Method
Find Method
Signup and view all the flashcards
First Method
First Method
Signup and view all the flashcards
FirstWhere Method
FirstWhere Method
Signup and view all the flashcards
Eloquent Model Table Name
Eloquent Model Table Name
Signup and view all the flashcards
Eloquent Model Primary Key
Eloquent Model Primary Key
Signup and view all the flashcards
Non-Incrementing Primary Key
Non-Incrementing Primary Key
Signup and view all the flashcards
Non-Integer Primary Key
Non-Integer Primary Key
Signup and view all the flashcards
UUID Primary Key
UUID Primary Key
Signup and view all the flashcards
Ordered UUIDs
Ordered UUIDs
Signup and view all the flashcards
Customizing UUID Generation
Customizing UUID Generation
Signup and view all the flashcards
ULID Primary Key
ULID Primary Key
Signup and view all the flashcards
Disable Timestamp Management
Disable Timestamp Management
Signup and view all the flashcards
Customizing Timestamp Format
Customizing Timestamp Format
Signup and view all the flashcards
Customizing Timestamp Column Names
Customizing Timestamp Column Names
Signup and view all the flashcards
Temporarily Disable Timestamp Updates
Temporarily Disable Timestamp Updates
Signup and view all the flashcards
Eloquent Model Database Connection
Eloquent Model Database Connection
Signup and view all the flashcards
Eloquent Model Default Attribute Values
Eloquent Model Default Attribute Values
Signup and view all the flashcards
Eloquent Strictness: Prevent Lazy Loading
Eloquent Strictness: Prevent Lazy Loading
Signup and view all the flashcards
Eloquent Strictness: Prevent Silently Discarding Attributes
Eloquent Strictness: Prevent Silently Discarding Attributes
Signup and view all the flashcards
Retrieving all Models
Retrieving all Models
Signup and view all the flashcards
Adding Constraints to Queries
Adding Constraints to Queries
Signup and view all the flashcards
Refreshing Eloquent Models
Refreshing Eloquent Models
Signup and view all the flashcards
Mass Assignable
Mass Assignable
Signup and view all the flashcards
What is the create
method used for?
What is the create
method used for?
Signup and view all the flashcards
What is the fill
method used for?
What is the fill
method used for?
Signup and view all the flashcards
Mass Assignment and JSON Columns
Mass Assignment and JSON Columns
Signup and view all the flashcards
What is the $guarded
property used for?
What is the $guarded
property used for?
Signup and view all the flashcards
Empty $guarded
array
Empty $guarded
array
Signup and view all the flashcards
Mass Assignment Exceptions
Mass Assignment Exceptions
Signup and view all the flashcards
What is the upsert
method used for?
What is the upsert
method used for?
Signup and view all the flashcards
How do I delete a Model?
How do I delete a Model?
Signup and view all the flashcards
What is the truncate
method used for?
What is the truncate
method used for?
Signup and view all the flashcards
Deleting by Primary Key
Deleting by Primary Key
Signup and view all the flashcards
What is forceDestroy
method used for?
What is forceDestroy
method used for?
Signup and view all the flashcards
Deleting using Queries
Deleting using Queries
Signup and view all the flashcards
What is Soft Deleting?
What is Soft Deleting?
Signup and view all the flashcards
How to Enable Soft Deletes
How to Enable Soft Deletes
Signup and view all the flashcards
Model Events
Model Events
Signup and view all the flashcards
Dispatched Events
Dispatched Events
Signup and view all the flashcards
Event Class Mapping
Event Class Mapping
Signup and view all the flashcards
Event Listeners
Event Listeners
Signup and view all the flashcards
Model Event Closures
Model Event Closures
Signup and view all the flashcards
Queueable Event Listeners
Queueable Event Listeners
Signup and view all the flashcards
Model Observers
Model Observers
Signup and view all the flashcards
Observer Methods
Observer Methods
Signup and view all the flashcards
Registering Observers
Registering Observers
Signup and view all the flashcards
Observer and Transactions
Observer and Transactions
Signup and view all the flashcards
What is model pruning?
What is model pruning?
Signup and view all the flashcards
How to schedule model pruning?
How to schedule model pruning?
Signup and view all the flashcards
What does 'model:prune' do?
What does 'model:prune' do?
Signup and view all the flashcards
How to specify models for pruning?
How to specify models for pruning?
Signup and view all the flashcards
How to exclude models from pruning?
How to exclude models from pruning?
Signup and view all the flashcards
Testing model pruning without actual deletion?
Testing model pruning without actual deletion?
Signup and view all the flashcards
What is mass pruning?
What is mass pruning?
Signup and view all the flashcards
How does mass pruning work?
How does mass pruning work?
Signup and view all the flashcards
What is the 'replicate' method?
What is the 'replicate' method?
Signup and view all the flashcards
How to exclude attributes when replicating?
How to exclude attributes when replicating?
Signup and view all the flashcards
What is a global scope?
What is a global scope?
Signup and view all the flashcards
How to generate a global scope?
How to generate a global scope?
Signup and view all the flashcards
How to apply a global scope to a model?
How to apply a global scope to a model?
Signup and view all the flashcards
How to remove a global scope?
How to remove a global scope?
Signup and view all the flashcards
What is a local scope?
What is a local scope?
Signup and view all the flashcards
How to define a local scope?
How to define a local scope?
Signup and view all the flashcards
What are findOrFail
and firstOrFail
methods used for?
What are findOrFail
and firstOrFail
methods used for?
Signup and view all the flashcards
How does Laravel handle ModelNotFoundException
?
How does Laravel handle ModelNotFoundException
?
Signup and view all the flashcards
What is the firstOrCreate
method?
What is the firstOrCreate
method?
Signup and view all the flashcards
What is the firstOrNew
method?
What is the firstOrNew
method?
Signup and view all the flashcards
What are aggregate methods in Eloquent?
What are aggregate methods in Eloquent?
Signup and view all the flashcards
How do you save a new model in Eloquent?
How do you save a new model in Eloquent?
Signup and view all the flashcards
What is the create
method?
What is the create
method?
Signup and view all the flashcards
What are fillable
and guarded
properties?
What are fillable
and guarded
properties?
Signup and view all the flashcards
How to update an existing model?
How to update an existing model?
Signup and view all the flashcards
What is the updateOrCreate
method?
What is the updateOrCreate
method?
Signup and view all the flashcards
What is the update
method?
What is the update
method?
Signup and view all the flashcards
How to examine model attribute changes?
How to examine model attribute changes?
Signup and view all the flashcards
What is Mass Assignment vulnerability?
What is Mass Assignment vulnerability?
Signup and view all the flashcards
What is the upsert
method?
What is the upsert
method?
Signup and view all the flashcards
What is the delete
method?
What is the delete
method?
Signup and view all the flashcards
What is the truncate
method?
What is the truncate
method?
Signup and view all the flashcards
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.