Database And Eloquent ORM
🚀 Database and Eloquent ORM in Laravel
Laravel provides a powerful database layer with two main features:
-
Query Builder – Fluent, chainable syntax for building SQL queries.
-
Eloquent ORM (Object Relational Mapper) – Active Record implementation for interacting with database tables as models.
Eloquent makes database interaction simple, readable, and expressive, reducing the need to write raw SQL queries.
🔹 1. Database Configuration
Database settings are stored in .env file:
➡️ Laravel supports MySQL, PostgreSQL, SQLite, SQL Server.
🔹 2. Running Database Migrations
Migrations = version control for databases.
Create migration:
Example migration:
Run migrations:
🔹 3. Eloquent ORM Basics
Each table has a Model.
📂 Example: app/Models/User.php
➡️ Table name → users (plural form by convention).
➡️ Primary key → id by default.
🔹 4. Eloquent CRUD Examples
✅ Insert Data
Or Mass Assignment:
✅ Retrieve Data
✅ Update Data
Or:
✅ Delete Data
Or:
🔹 5. Query Builder Examples
🔹 6. Relationships in Eloquent
Eloquent makes it easy to define table relationships.
✅ One to One
✅ One to Many
✅ Many to Many
🔹 7. Eloquent Accessors & Mutators
-
Accessor → format data when retrieving.
-
Mutator → modify data before saving.
🔹 8. Eloquent Scopes
Reusable query logic.
Usage:
📌 Summary
-
Migrations → database version control.
-
Eloquent ORM → model-based data interaction.
-
CRUD operations → simple and expressive.
-
Relationships → one-to-one, one-to-many, many-to-many.
-
Accessors, Mutators, and Scopes → powerful customization.
Laravel’s Eloquent makes database handling easier, faster, and cleaner.