Skip to main content
Laravel Basics Tutorial
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 $fillable array.

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 named posts, 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
1
php artisan make:model Post

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
12345678910111213141516
use App\Models\Post;

// Get ALL posts in the table
$all_posts = Post::all();

// Find one specific post by its ID (Primary Key)
$single_post = Post::find(5);

// Filter data with 'Where' clauses
$active_posts = Post::where('is_published', true)->get();

// Complex filtering and ordering
$recent_posts = Post::where('views', '>', 100)
                    ->orderBy('created_at', 'desc')
                    ->take(10)
                    ->get();

*(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 the save() method.
php
123456
use App\Models\Post;

$post = new Post();
$post->title = "My First Blog";
$post->body = "This is the content of the blog.";
$post->save(); // Laravel translates this into an INSERT SQL command!

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
123456789
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    // ONLY these columns are allowed to be bulk-inserted
    protected $fillable = [&#039;title', 'body'];
}

8. Updating and Deleting Data

Updating:
php
1234
// Find the post, change the title, save it back
$post = Post::find(1);
$post->title = "Updated Title";
$post->save(); // Laravel translates this into an UPDATE SQL command

Deleting:

php
12
$post = Post::find(1);
$post->delete(); // Laravel translates this into a DELETE SQL command

9. Best Practices

  • Fail Gracefully: Instead of using Post::find($id), professional developers use Post::findOrFail($id). If the user types a URL for an ID that doesn't exist, findOrFail automatically 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. The where() clause just prepares the query. You MUST append ->get() to actually execute the query and fetch the data!

11. Exercises

  1. 1. Explain why Laravel forces developers to use the $fillable array before allowing Model::create() to work. What security vulnerability does it prevent?

12. Coding Challenges

  • Challenge: Write the Eloquent syntax required to find all Users whose status is 'banned', order them by their created_at date 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 $fillable property 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 the DB::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.

17. Next Chapter Recommendation

We know how routing, controllers, views, and the database work in isolation. Now, let's wire them all together. Proceed to Chapter 10: Building CRUD Applications in Laravel.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·