Eloquent in Laravel
86 Questions
0 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

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?

  • app/Models (correct)
  • app/Database
  • database/Models
  • resources/Models

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?

<p>To create a migration file alongside the model. (A)</p> Signup and view all the answers

What naming convention does Eloquent use to determine the database table name from a model?

<p>It uses the snake case, plural form of the model name. (D)</p> Signup and view all the answers

What command provides an overview of all a model's attributes and relationships?

<p>model:show (B)</p> Signup and view all the answers

Which of the following options can be generated using the make:model command?

<p>Models, migrations, factories, and seeders (A)</p> Signup and view all the answers

What characteristic does an Eloquent model NOT possess?

<p>Ability to interact directly with the database schema. (C)</p> Signup and view all the answers

What property needs to be set to use a non-incrementing primary key in an Eloquent model?

<p>$incrementing (D)</p> Signup and view all the answers

What trait should be used in a model to implement UUID as the primary key?

<p>HasUuids (C)</p> Signup and view all the answers

Which property must be defined to customize the format of model timestamps?

<p>$dateFormat (D)</p> Signup and view all the answers

How can you prevent Eloquent from automatically managing the created_at and updated_at timestamps?

<p>Set $timestamps property to false (D)</p> Signup and view all the answers

What is the maximum length of a UUID used as a primary key in Eloquent?

<p>36 (D)</p> Signup and view all the answers

Which property should be defined to specify a different primary key column for a model?

<p>$primaryKey (D)</p> Signup and view all the answers

What method is used to refresh an instance of an Eloquent model retrieved from the database?

<p>refresh (C)</p> Signup and view all the answers

What must be set on a model to utilize ULIDs instead of UUIDs?

<p>HasUlids trait (D)</p> Signup and view all the answers

Which method can be invoked to disable lazy loading in Eloquent?

<p>preventLazyLoad (A)</p> Signup and view all the answers

What is the main limitation of Eloquent regarding composite primary keys?

<p>They are not supported (B)</p> Signup and view all the answers

What property can be defined to specify a default database connection for a model?

<p>$connection (B)</p> Signup and view all the answers

What must you define to set default values for model attributes?

<p>$attributes (B)</p> Signup and view all the answers

Using which method will allow operations on a model without modifying its updated_at timestamp?

<p>withoutTimestamps (D)</p> Signup and view all the answers

What is the main purpose of the refresh method in Eloquent?

<p>To re-hydrate the existing model with fresh data from the database. (D)</p> Signup and view all the answers

Which method is recommended for handling large numbers of Eloquent models to avoid memory issues?

<p>chunk (C)</p> Signup and view all the answers

What does the cursor method do in Eloquent collections?

<p>It hydrates models as they are iterated over. (C)</p> Signup and view all the answers

When should you use the chunkById method?

<p>When filtering results based on a column that you are updating. (C)</p> Signup and view all the answers

How does the lazy method differ from the chunk method?

<p>The lazy method returns records as a single stream instead of invoking a closure. (A)</p> Signup and view all the answers

What is the purpose of the subquery functionality in Eloquent?

<p>To combine information from related tables in a single query. (A)</p> Signup and view all the answers

What will the findOr method return if no results are found?

<p>The result of a provided closure. (A)</p> Signup and view all the answers

Which method allows you to remove models from a collection using a closure?

<p>reject (A)</p> Signup and view all the answers

What is the best use case for the lazyById method?

<p>When updating records while iterating through the results. (C)</p> Signup and view all the answers

How does using chunking improve memory efficiency?

<p>By retrieving and processing small subsets of records at a time. (B)</p> Signup and view all the answers

What does the orderBy method support in the context of Eloquent?

<p>Ordering results based on subqueries. (C)</p> Signup and view all the answers

What is a limitation of the cursor method when processing large datasets?

<p>It can still run out of memory due to PDO caching. (C)</p> Signup and view all the answers

What does the find method return?

<p>A single model instance matching the given primary key. (B)</p> Signup and view all the answers

What property needs to be defined on an Eloquent model to start listening to model events?

<p>$dispatchesEvents (A)</p> Signup and view all the answers

Which event is dispatched when an existing model is modified and the save method is called?

<p>updating (A)</p> 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?

<p>ShouldHandleEventsAfterCommit (D)</p> Signup and view all the answers

What command is used to create a new observer class in Laravel?

<p>make:observer (A)</p> Signup and view all the answers

What method is used to temporarily mute all events fired by a model?

<p>withoutEvents (C)</p> Signup and view all the answers

Where can observers be manually registered in an application?

<p>In the AppServiceProvider class (D)</p> Signup and view all the answers

What is dispatched when a model is created or updated, regardless of attribute changes?

<p>saving (A)</p> Signup and view all the answers

What method can be used to save a model without dispatching any events?

<p>saveQuietly (C)</p> Signup and view all the answers

Which event type is dispatched before changes to the model are saved?

<p>creating (C)</p> Signup and view all the answers

What is the purpose of using closures when registering model events?

<p>To handle events without creating separate classes (D)</p> Signup and view all the answers

What method is used to insert a new record in the database when attributes are mass assignable?

<p>create (C)</p> Signup and view all the answers

What does the $guarded property represent in a model?

<p>Attributes that are not mass assignable (C)</p> Signup and view all the answers

What would happen if an attribute is not in the $fillable array during a mass assignment?

<p>The attribute is silently discarded (D)</p> Signup and view all the answers

Which method should be invoked to handle mass assignment exceptions?

<p>preventSilentlyDiscardingAttributes (D)</p> Signup and view all the answers

What is the purpose of Eloquent's upsert method?

<p>To create or update records in a single operation (C)</p> Signup and view all the answers

How can you delete all associated records of a model at once?

<p>truncate (A)</p> Signup and view all the answers

What happens to a model when it is soft deleted?

<p>A record indicating the deletion time is retained (C)</p> Signup and view all the answers

Which trait must be added to a model to enable soft deleting?

<p>Illuminate.Database.Eloquent.SoftDeletes (D)</p> Signup and view all the answers

How do you restore a soft deleted model?

<p>restore (A)</p> Signup and view all the answers

Which method will permanently delete a soft deleted model?

<p>forceDelete (A)</p> Signup and view all the answers

What does the withTrashed method do?

<p>Includes soft deleted models in the query results (D)</p> Signup and view all the answers

How can you retrieve only soft deleted models?

<p>onlyTrashed (D)</p> Signup and view all the answers

What trait is used to periodically delete models that are no longer needed?

<p>Illuminate.Database.Eloquent.Prunable (D)</p> Signup and view all the answers

When marking models as Prunable, what method must be implemented?

<p>prunable (A)</p> Signup and view all the answers

What is the purpose of the model:prune Artisan command?

<p>To automatically detect and delete unused resources associated with prunable models. (C)</p> Signup and view all the answers

Which option allows you to prevent certain models from being pruned?

<p>--except (D)</p> Signup and view all the answers

What trait must models use for mass deletion without triggering the pruning process?

<p>Illuminate\Database\Eloquent\MassPrunable (D)</p> Signup and view all the answers

Which of the following statements is true about global scopes?

<p>Global scopes can add constraints to all queries for a given model. (C)</p> Signup and view all the answers

What method is invoked to register a new global scope to a model?

<p>addGlobalScope (A)</p> Signup and view all the answers

What is the function of the withoutGlobalScope method?

<p>To remove a specific global scope from a query. (D)</p> Signup and view all the answers

What happens when a model is replicated using the replicate method?

<p>An unsaved copy of the model instance is created. (A)</p> Signup and view all the answers

What happens when a model is not found using the findOrFail method?

<p>It throws a ModelNotFoundException. (C)</p> Signup and view all the answers

Which method can be used to define a dynamic scope that accepts parameters?

<p>scope (A)</p> Signup and view all the answers

How can you quickly check if two models are identical?

<p>Using the is and isNot methods. (A)</p> Signup and view all the answers

What is the primary purpose of the firstOrCreate method?

<p>To locate a record and insert it only if it is not found. (B)</p> Signup and view all the answers

Which method would you use to ensure a model instance is returned without saving it to the database?

<p>firstOrNew (A)</p> Signup and view all the answers

Which Eloquent event is dispatched when an existing model is retrieved from the database?

<p>retrieved (A)</p> Signup and view all the answers

How can you update a model that already exists in the database?

<p>By manually setting the attributes and calling save. (A)</p> Signup and view all the answers

What is the purpose of local scopes in Eloquent?

<p>To define common sets of constraints that are reusable across queries. (D)</p> Signup and view all the answers

Which command would you use to generate a new global scope in Laravel?

<p>make:scope (A)</p> Signup and view all the answers

What should be specified on a model class before using the create method?

<p>The fillable or guarded property. (D)</p> Signup and view all the answers

What does the updateOrCreate method do?

<p>Updates existing models or creates a new one if not found. (A)</p> Signup and view all the answers

What does the higher order orWhere method help with in Eloquent?

<p>It allows chaining of multiple scopes fluently without closures. (D)</p> Signup and view all the answers

What does the isDirty method indicate about a model's attributes?

<p>Some attributes have been modified since retrieval. (A)</p> Signup and view all the answers

What method should be called to add custom clauses to a query when writing a global scope?

<p>apply (B)</p> Signup and view all the answers

Which method would you use to retrieve the original attributes of a model?

<p>getOriginal (D)</p> Signup and view all the answers

What is the purpose of the --pretend option in the model:prune command?

<p>To simulate the pruning process and display what would be deleted. (B)</p> Signup and view all the answers

In what situation would you use the count method in Eloquent?

<p>To determine the number of records matching a query. (D)</p> Signup and view all the answers

What happens to the model's timestamps when the save method is called?

<p>They are updated automatically. (A)</p> Signup and view all the answers

What is the purpose of the max method when used with Eloquent models?

<p>To return the maximum value of a specified column. (A)</p> Signup and view all the answers

When would a ModelNotFoundException be thrown?

<p>When using the findOrFail method and no record is found. (D)</p> Signup and view all the answers

Why is mass assignment protection necessary in Eloquent models?

<p>To prevent unexpected database changes from user input. (D)</p> Signup and view all the answers

Flashcards

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?

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?

You can use the 'make:model' Artisan command to generate a new Eloquent model.

Model with Migration?

You can use the '--migration' or '-m' flag with 'make:model' to generate both a model and a database migration.

Signup and view all the flashcards

What is the 'model:show' command?

It displays your model's attributes, relationships, and other information, useful for understanding your model's structure.

Signup and view all the flashcards

Eloquent Table Naming Convention

By default, Eloquent assumes the table name is the plural, snake case version of your model name.

Signup and view all the flashcards

Overriding Table Name

If your table doesn't follow the default convention, you can manually specify the table name in your Model.

Signup and view all the flashcards

Why use Eloquent?

Eloquent simplifies database interaction, making code cleaner, more readable, and less prone to errors.

Signup and view all the flashcards

Fresh Method

Refetches a model from the database without affecting the existing model instance.

Signup and view all the flashcards

Refresh Method

Updates the existing model with fresh data and refreshes its loaded relationships.

Signup and view all the flashcards

Eloquent Collection

A class extending Laravel's base Collection class providing helpful methods for interacting with collections of Eloquent models.

Signup and view all the flashcards

Reject Method

Removes models from a collection based on a provided condition.

Signup and view all the flashcards

Chunking Results

A method to process large numbers of Eloquent records efficiently by retrieving them in smaller chunks.

Signup and view all the flashcards

Chunk Method

Retrieves a subset of models, passing them to a closure for processing, reducing memory usage.

Signup and view all the flashcards

ChunkById Method

Retrieves chunks of models based on their id column, useful for filtering and updating.

Signup and view all the flashcards

Lazy Method

Retrieves models in chunks behind the scenes, returning a LazyCollection for efficient interaction.

Signup and view all the flashcards

LazyById Method

Similar to 'chunkById', but works with 'lazy' collections, retrieving models based on their id.

Signup and view all the flashcards

Cursor Method

Retrieves results from the database in a single query, hydrating Eloquent models only when iterated.

Signup and view all the flashcards

Subquery Selects

Allows pulling information from related tables in a single query using subqueries.

Signup and view all the flashcards

Subquery Ordering

Supports using subqueries within the orderBy function, allowing for sorting based on related data.

Signup and view all the flashcards

Find Method

Retrieves a single model instance based on the given ID.

Signup and view all the flashcards

First Method

Retrieves the first model matching the query criteria.

Signup and view all the flashcards

FirstWhere Method

Retrieves the first model matching the provided criteria.

Signup and view all the flashcards

Eloquent Model Table Name

Eloquent automatically assumes a table name based on the model name. For example, the User model would correspond to a users table. However, if the table doesn't follow this convention, you can manually specify the table name using the table property on the model.

Signup and view all the flashcards

Eloquent Model Primary Key

By default, Eloquent assumes each model's table has a primary key column named id. To use a different column as the primary key, define the primaryKey property in your model.

Signup and view all the flashcards

Non-Incrementing Primary Key

Eloquent assumes the primary key is an incrementing integer, but you can use a non-incrementing or non-numeric primary key by setting the incrementing property to false.

Signup and view all the flashcards

Non-Integer Primary Key

If your primary key is not an integer, you need to tell Eloquent by setting the keyType property to string.

Signup and view all the flashcards

UUID Primary Key

Instead of using standard numeric IDs, you can use UUIDs (Universally Unique Identifiers) for unique identification. To use UUIDs as primary keys in Eloquent, you can use the HasUuids trait.

Signup and view all the flashcards

Ordered UUIDs

By default, the HasUuids trait generates ordered UUIDs, which are more efficient for indexing in databases.

Signup and view all the flashcards

Customizing UUID Generation

You can override the default UUID generation process by defining a newUniqueId method in your model.

Signup and view all the flashcards

ULID Primary Key

ULIDs are similar to UUIDs but shorter (26 characters) and also lexicographically sortable. You can use the HasUlids trait to utilize ULIDs as your primary key.

Signup and view all the flashcards

Disable Timestamp Management

Eloquent automatically manages created_at and updated_at timestamps for your models. To disable this, set the $timestamps property to false.

Signup and view all the flashcards

Customizing Timestamp Format

You can control how timestamps are stored and formatted by setting the $dateFormat property.

Signup and view all the flashcards

Customizing Timestamp Column Names

You can rename the created_at and updated_at columns by defining CREATED_AT and UPDATED_AT constants in your model.

Signup and view all the flashcards

Temporarily Disable Timestamp Updates

Use the withoutTimestamps method with a closure to perform model operations without updating the updated_at timestamp.

Signup and view all the flashcards

Eloquent Model Database Connection

By default, Eloquent models use the default database connection configured in your application. You can specify a different connection for a model by defining the $connection property.

Signup and view all the flashcards

Eloquent Model Default Attribute Values

You can define default values for model attributes by specifying them in the $attributes property.

Signup and view all the flashcards

Eloquent Strictness: Prevent Lazy Loading

The preventLazyLoading method allows you to prevent relationships from being loaded lazily. This can help avoid unexpected errors that might occur due to relationships being loaded in your code.

Signup and view all the flashcards

Eloquent Strictness: Prevent Silently Discarding Attributes

The preventSilentlyDiscardingAttributes method enables the throwing of exceptions when you try to fill an attribute not defined in the fillable array, ensuring that your code doesn't silently discard information.

Signup and view all the flashcards

Retrieving all Models

You can retrieve all models from the database by using the all method on your model.

Signup and view all the flashcards

Adding Constraints to Queries

Use Eloquent's query builder functionality to add constraints to your queries before retrieving data with the get method.

Signup and view all the flashcards

Refreshing Eloquent Models

You can refresh an existing model from the database using the fresh or refresh methods.

Signup and view all the flashcards

Mass Assignable

Attributes that can be directly filled using mass assignment methods like create and fill. They are defined in the $fillable array of the model.

Signup and view all the flashcards

What is the create method used for?

The create method inserts a new record into the database based on the given attributes and returns the newly created model instance.

Signup and view all the flashcards

What is the fill method used for?

Populates a pre-existing model instance with an array of attributes.

Signup and view all the flashcards

Mass Assignment and JSON Columns

Each JSON column's mass assignable key must be explicitly defined in the model's $fillable array to allow assignments.

Signup and view all the flashcards

What is the $guarded property used for?

The $guarded property defines attributes that are not mass assignable. By default, it's set to ['*'], meaning all attributes are protected.

Signup and view all the flashcards

Empty $guarded array

Setting the $guarded property to an empty array allows all attributes to be mass assigned.

Signup and view all the flashcards

Mass Assignment Exceptions

Laravel normally silently discards unfillable attributes during mass assignment. To catch these errors, call the preventSilentlyDiscardingAttributes method in your AppServiceProvider.

Signup and view all the flashcards

What is the upsert method used for?

Performs an atomic operation to either create or update a record based on the given conditions.

Signup and view all the flashcards

How do I delete a Model?

Call the delete method on a model instance to remove it from the database.

Signup and view all the flashcards

What is the truncate method used for?

Deletes all records associated with the model and resets the table's auto-incrementing IDs.

Signup and view all the flashcards

Deleting by Primary Key

Use the destroy method and provide the primary key(s) to delete models without explicitly retrieving them.

Signup and view all the flashcards

What is forceDestroy method used for?

Permanently deletes a soft deleted model from the database.

Signup and view all the flashcards

Deleting using Queries

Use Eloquent queries to delete models matching specific criteria.

Signup and view all the flashcards

What is Soft Deleting?

A mechanism to logically delete records by setting a deleted_at timestamp, keeping the record in the database but marking it as deleted.

Signup and view all the flashcards

How to Enable Soft Deletes

Add the SoftDeletes trait to your model and include the deleted_at column in your database table using the schema builder.

Signup and view all the flashcards

Model Events

Eloquent models dispatch events at key points during their lifecycle (creation, updating, saving, etc.). These events can be used to trigger custom actions or logic.

Signup and view all the flashcards

Dispatched Events

Model events are dispatched during different stages of a model's lifecycle, like creation, updating, or saving. These events can be captured and handled to perform custom actions.

Signup and view all the flashcards

Event Class Mapping

To listen for events, you define a $dispatchesEvents property on your model, mapping specific events to your own event classes.

Signup and view all the flashcards

Event Listeners

Event listeners are functions or classes that respond to specific model events, allowing you to execute code when those events occur.

Signup and view all the flashcards

Model Event Closures

Instead of using custom event classes, you can register closures directly within the booted method of your model to handle events.

Signup and view all the flashcards

Queueable Event Listeners

You can register event listeners to be executed in the background using the queue, allowing for asynchronous execution. This is useful for tasks that might take longer to complete.

Signup and view all the flashcards

Model Observers

Observers are classes that group multiple event listeners together. You can create one observer to handle various events for a single model.

Signup and view all the flashcards

Observer Methods

Observer methods are named after the corresponding Eloquent events they should handle. Each method receives the affected model as an argument.

Signup and view all the flashcards

Registering Observers

You can register observers using the ObservedBy attribute on your model or manually by invoking the observe method on the model.

Signup and view all the flashcards

Observer and Transactions

If you want an observer to execute its event handlers only after a database transaction is committed, you can implement the ShouldHandleEventsAfterCommit interface on your observer.

Signup and view all the flashcards

What is model pruning?

Deleting additional resources associated with a model, such as stored files, before permanently removing it from the database.

Signup and view all the flashcards

How to schedule model pruning?

Use the 'model:prune' Artisan command in your application's 'routes/console.php' file. You can set the frequency at which it runs.

Signup and view all the flashcards

What does 'model:prune' do?

Automatically detects 'Prunable' models within your application's 'app/Models' directory and prunes them based on your configuration.

Signup and view all the flashcards

How to specify models for pruning?

Use the '--model' option for model classes that are not in the default 'app/Models' directory.

Signup and view all the flashcards

How to exclude models from pruning?

Use the '--except' option to prevent specific models from being pruned.

Signup and view all the flashcards

Testing model pruning without actual deletion?

Use the '--pretend' option with the 'model:prune' command. It will report how many records would be pruned.

Signup and view all the flashcards

What is mass pruning?

Deleting models using mass-deletion queries, bypassing individual deletion methods.

Signup and view all the flashcards

How does mass pruning work?

Models with the "Illuminate\Database\Eloquent\MassPrunable" trait are deleted using mass-deletion queries, skipping individual pruning methods.

Signup and view all the flashcards

What is the 'replicate' method?

Creates an unsaved copy of an existing model instance, preserving its attributes.

Signup and view all the flashcards

How to exclude attributes when replicating?

Pass an array of attributes to the 'replicate' method to exclude them from the new model instance.

Signup and view all the flashcards

What is a global scope?

A mechanism to add constraints to all queries for a given model, like a global filter.

Signup and view all the flashcards

How to generate a global scope?

Use the 'make:scope' Artisan command to create a new global scope class in your application's 'app/Models/Scopes' directory.

Signup and view all the flashcards

How to apply a global scope to a model?

Add the 'ScopedBy' attribute to the model or use the 'addGlobalScope' method within the 'booted' method of the model.

Signup and view all the flashcards

How to remove a global scope?

Use the 'withoutGlobalScope' method for specific queries or the 'withoutGlobalScopes' method to remove all global scopes.

Signup and view all the flashcards

What is a local scope?

A reusable set of query constraints that can be applied to a model, like a custom shortcut.

Signup and view all the flashcards

How to define a local scope?

Create a method in the Eloquent model class with the prefix 'scope' and define your query constraints.

Signup and view all the flashcards

What are findOrFail and firstOrFail methods used for?

These methods attempt to retrieve the first model matching the query. If no model is found, they throw an Illuminate\Database\Eloquent\ModelNotFoundException.

Signup and view all the flashcards

How does Laravel handle ModelNotFoundException?

If not caught manually, a 404 HTTP response is automatically sent back to the client, notifying the user that the requested resource doesn't exist.

Signup and view all the flashcards

What is the firstOrCreate method?

It attempts to locate a record using given criteria. If not found, a new record is inserted with the provided attributes.

Signup and view all the flashcards

What is the firstOrNew method?

It attempts to locate a record, and if not found, returns a new model instance, but doesn't save it to the database yet.

Signup and view all the flashcards

What are aggregate methods in Eloquent?

Methods like count, sum, max, which return a single value instead of an Eloquent model.

Signup and view all the flashcards

How do you save a new model in Eloquent?

Instantiate a model, set its attributes, and call the save method.

Signup and view all the flashcards

What is the create method?

A shortcut for inserting and saving a new model with a single line of code.

Signup and view all the flashcards

What are fillable and guarded properties?

They control which model attributes are allowed for mass assignment, preventing vulnerabilities.

Signup and view all the flashcards

How to update an existing model?

Retrieve the model, set the desired attributes, and call the save method.

Signup and view all the flashcards

What is the updateOrCreate method?

It updates an existing model or creates a new one if it doesn't exist, saving you the need to manually call save.

Signup and view all the flashcards

What is the update method?

This method updates models that match a given query, returning the number of affected rows.

Signup and view all the flashcards

How to examine model attribute changes?

Use methods like isDirty, isClean, wasChanged, and getOriginal to check model attribute state.

Signup and view all the flashcards

What is Mass Assignment vulnerability?

A security risk where malicious users can modify unexpected database fields through HTTP requests.

Signup and view all the flashcards

What is the upsert method?

It performs an atomic operation, updating a record if it exists, otherwise creating a new one based on given conditions.

Signup and view all the flashcards

What is the delete method?

It removes a model from the database.

Signup and view all the flashcards

What is the truncate method?

This method deletes all records from the model's table and resets auto-incrementing IDs.

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 extend Illuminate\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 to flights 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 and updated_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 and UPDATED_AT constants to customize timestamp column names.
  • Use withoutTimestamps to avoid modifying updated_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 in AppServiceProvider 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() and get() return Illuminate\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() or chunkById() to efficiently process large numbers of records in chunks.
  • Use chunk() for simpler iteration; use chunkById() to incrementally process models by ID.
  • Use lazy() or lazyById() 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() and addSelect() 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 define fillable or guarded).
  • 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 and deleted_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 or MassPrunable trait).
  • Implement a pruning method that constructs a query for deleting models, and model: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 the saveQuietly() method to modify operations without triggering events.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

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.

More Like This

Laravel Eloquent ORM
10 questions

Laravel Eloquent ORM

AccessibleJasper avatar
AccessibleJasper
Use Quizgecko on...
Browser
Browser