What is the Eloquent ORM?
Laravel includes an object-relational mapper (ORM) called Eloquent. Eloquent makes it easy to interact with the database and implements the Active Record pattern. With Eloquent, you create a “model” class that corresponds to each table in the database. You retrieve, insert, update, and delete records through the model.Before using Eloquent, configure your database connection in
config/database.php.
By default, the DB_* settings in your .env file are used.Creating a model
Generate a new model with themake:model Artisan command.
-m option.
app/Models directory.
Model-to-table mapping
Eloquent infers the table name from the class name automatically. The class name converted to a snake_case plural becomes the table name.
If your table name does not follow the naming convention, define the
$table property on the model to specify it explicitly.
Timestamps
By default, Eloquent automatically manages thecreated_at and updated_at columns.
Include $table->timestamps() in your migration and Eloquent will set these values for you when the model is saved or updated.
To disable automatic timestamp management, set $timestamps to false.
Mass assignment protection
When saving data in bulk with Eloquent, you must configure mass assignment protection.fillable
Use the$fillable property to specify which columns may be mass assigned.
guarded
Conversely, use$guarded to specify which columns cannot be mass assigned.
Eloquent query execution flow
Here is how a query such asUser::where()->get() is executed internally.
Basic CRUD operations
Retrieving records (Read)
Retrieve every record:Creating records (Create)
Use thecreate method to insert a single record (you must configure $fillable):
Updating records (Update)
Retrieve the model, change its values, and callsave to persist the update.
update to update multiple columns at once.
Deleting records (Delete)
Use thedelete method to remove a record.
Common query methods
Practical example: working with the Post model
Here is a controller that operates on theposts table created by a migration.
The model event lifecycle
Here are the events fired when you callsave(). Different events fire depending on whether it is a create or an update, but saving and saved fire in both cases.
Next steps
Migrations
A refresher on creating the tables Eloquent uses with migrations.