CHAPTER 09
Beginner
Eloquent ORM Basics
Updated: May 14, 2026
25 min read
# CHAPTER 9
Eloquent ORM Basics
1. Introduction
Writing raw SQL queries (SELECT * FROM users WHERE status = 'active') inside your PHP code is tedious, insecure if not done properly, and difficult to maintain if you switch databases. Laravel solves this with Eloquent ORM (Object-Relational Mapper). Eloquent transforms your database tables into intelligent PHP Objects. In this chapter, we will learn how to interact with our database using beautiful, readable PHP syntax instead of writing a single line of raw SQL.
2. Learning Objectives
By the end of this chapter, you will be able to:- Define what an ORM is.
- Generate Eloquent Models using Artisan.
- Perform database queries using Eloquent syntax.
-
Understand Mass Assignment and the
$fillablearray.
3. Beginner-Friendly Explanation
Imagine an accountant (your PHP code) who only speaks English, trying to talk to a foreign bank manager (the Database) who only speaks SQL. Normally, the accountant has to look up words in an English-to-SQL dictionary to ask for financial records. It is slow and prone to errors. Eloquent ORM is a highly-paid professional translator. The accountant just speaks plain English to Eloquent: *"Hey, give me all users over the age of 18."* (User::where('age', '>', 18)->get();). Eloquent instantly translates this into flawless SQL, talks to the bank, gets the data, translates it back into PHP Objects, and hands it to the accountant.
4. What is a Model?
In MVC, the Model represents a single table in the database. If your database has a table namedposts, your Model will be named Post (singular, capitalized).
Laravel is smart enough to know that the Post model automatically manages the posts table.
Create the Model:
bash
This creates app/Models/Post.php.
5. Fetching Data (Read)
Now that we have a Model, we can fetch data from the database with extreme ease in our Controllers.
php
*(Notice how readable this is! It reads exactly like English).*
6. Inserting Data (Create)
Creating a new record in the database is incredibly intuitive. You instantiate a new Model object, assign values to its properties, and call thesave() method.
php
7. Mass Assignment (The $fillable Array)
Instead of assigning properties line-by-line, you often want to save an entire array of form data instantly: Post::create($request->all());.
However, this is dangerous. A hacker could inject 'is_admin' => 1 into the form and make themselves an admin!
To protect against this, Laravel requires you to explicitly define which columns are safe to be bulk-filled using the $fillable array inside the Model.
In app/Models/Post.php:
php
8. Updating and Deleting Data
Updating:
php
Deleting:
php
9. Best Practices
-
Fail Gracefully: Instead of using
Post::find($id), professional developers usePost::findOrFail($id). If the user types a URL for an ID that doesn't exist,findOrFailautomatically throws a clean 404 Error page instead of crashing the application.
10. Common Mistakes
-
Forgetting
get(): Beginners often write$users = User::where('age', 18);and wonder why no data appears. Thewhere()clause just prepares the query. You MUST append->get()to actually execute the query and fetch the data!
11. Exercises
-
1.
Explain why Laravel forces developers to use the
$fillablearray before allowingModel::create()to work. What security vulnerability does it prevent?
12. Coding Challenges
-
Challenge: Write the Eloquent syntax required to find all Users whose
statusis 'banned', order them by theircreated_atdate in descending order, and retrieve the results.
13. MCQs with Answers
Question 1
What is Eloquent in Laravel?
Question 2
Which Eloquent method is used to retrieve a single record from the database based on its Primary Key (ID)?
14. Interview Questions
-
Q: What is Mass Assignment Vulnerability, and how does Eloquent's
$fillableproperty mitigate it?
- Q: Compare writing a complex database query in raw PDO PHP versus writing it using Laravel's Eloquent ORM. What are the maintainability advantages of Eloquent?
15. FAQs
Q: What if I have a massive, highly complex query that Eloquent can't handle? A: In very rare cases where Eloquent is too slow or you have a 50-line custom SQL join, Laravel allows you to bypass the ORM and run raw SQL using theDB::select('RAW SQL HERE') facade.
16. Summary
In Chapter 9, we unlocked the true power of Laravel. Eloquent ORM abstracts away the dangerous, repetitive task of writing raw SQL. By treating database records as intelligent PHP Objects, we can perform complex CRUD operations with single lines of highly readable code. By understanding critical security features like$fillable for mass assignment protection, we ensure our database interactions are both elegant and secure.