Models and Eloquent ORM
β± Estimated reading time: 2 min
Models in Laravel represent the data layer of an application. They interact with the database and contain the business logic related to data. Laravel uses Eloquent ORM (ObjectβRelational Mapping), which allows developers to work with database records as PHP objects in a simple and expressive way.
1. What Is a Model?
A model represents a database table and is responsible for:
-
Retrieving data
-
Inserting new records
-
Updating existing records
-
Deleting records
Models are stored in:
Example:
A User model typically represents the users table.
2. Creating a Model
Laravel provides an Artisan command to create models:
This creates:
To create a model with a migration:
3. Basic Model Structure
Example model:
By convention:
-
Model name β Singular (
Post) -
Table name β Plural (
posts)
4. Mass Assignment
To protect against unwanted data insertion, Laravel uses mass assignment rules.
Or:
5. Retrieving Data with Eloquent
Get All Records
Find by ID
Conditional Queries
6. Inserting Data
Or using mass assignment:
7. Updating Data
Or:
8. Deleting Data
9. Eloquent Relationships
Eloquent makes database relationships easy.
One-to-One
One-to-Many
Many-to-Many
10. Eloquent Query Builder
Chained queries:
11. Timestamps
By default, Eloquent manages timestamps:
-
created_at -
updated_at
To disable:
Conclusion
Models and Eloquent ORM provide a powerful and intuitive way to interact with databases in Laravel. By using expressive syntax and built-in relationships, Eloquent simplifies database operations while maintaining clean, readable, and maintainable code.
Register Now
Share this Post
β Back to Tutorials