What is Eloquent?
Laravel includes Eloquent, an object-relational mapper (ORM) that makes database interaction straightforward. Eloquent implements the Active Record pattern. With Eloquent, each database table has a corresponding “model” class. You use the model to retrieve, insert, update, and delete records in that table.Before using Eloquent, configure your database connection in
config/database.php. By default, Laravel reads the DB_* values from your .env file.Creating a model
Use themake:model Artisan command to generate a new model:
-m flag:
app/Models directory:
Table naming conventions
Eloquent automatically infers the table name from the class name — it converts the class name to snake_case and pluralizes it:
If your table name does not follow this convention, define a
$table property on the model:
Timestamps
Eloquent automatically managescreated_at and updated_at columns. If you add $table->timestamps() in your migration, Eloquent sets the values automatically when you save or update a model.
To disable automatic timestamp management:
Mass assignment protection
When inserting records in bulk, you need to configure mass assignment protection.fillable
Specify which columns are mass-assignable using the$fillable property:
guarded
Alternatively, use$guarded to specify which columns should not be mass-assignable:
Basic CRUD operations
Reading records
Retrieve all records:Creating records
Use thecreate method to insert a single record (requires $fillable to be configured):
Updating records
Retrieve the model, change its properties, then callsave:
update method to update multiple columns at once:
Deleting records
Calldelete on a retrieved model:
Common query methods
Practical example: a PostController
Here is a controller that uses thePost model to handle typical blog post operations:
Next steps
Database migrations
Review how to create the tables that Eloquent models map to.