Learn Laravel · 6/17

Eloquent ORM Basics: Talking to Your Database

8 min read

Welcome back! So, you've set up your Laravel project, and it's looking great. But a web application that can't remember anything is like a goldfish with a shorter-than-average memory span. We need a way to store and retrieve information permanently. This is where your database comes in, and Laravel has a beautiful and powerful tool called Eloquent ORM to help us communicate with it.

What in the World is an ORM?

The Problem: Writing raw SQL queries can be tedious, repetitive, and sometimes, a little messy. Imagine having to write SELECT * FROM users WHERE id = 1 or INSERT INTO posts (title, content) VALUES ('My First Post', 'Hello world!') every single time you need to interact with your database. It also makes your application more dependent on a specific database system (like MySQL). If you wanted to switch to another system (like PostgreSQL), you might have to rewrite a lot of your queries.

The Solution: An ORM, which stands for Object-Relational Mapper, is a programming technique that lets you interact with your database as if you were just working with PHP objects. Instead of writing raw SQL, you call methods on these objects. Eloquent is Laravel's implementation of an ORM.

Think of it like this: You have a massive, perfectly organized library (your database). Instead of having to know the exact shelf, row, and book number (raw SQL), you can just ask the librarian (Eloquent) "Hey, can you get me the book 'The Hitchhiker's Guide to the Galaxy' by Douglas Adams?". The librarian knows exactly where to go and brings it right to you. You get the book (data) without needing to know the library's complex filing system.

Eloquent makes your life as a developer much easier, more intuitive, and keeps your code clean and readable.


1. Creating Models & Understanding Naming Conventions ✨

At the heart of Eloquent is the Model. An Eloquent model is just a PHP class that represents a single table in your database. Each instance of that model class corresponds to a row within that table.

The Problem: How do we tell Laravel that a User class should talk to the users table, or a BlogPost class should talk to the blog_posts table? Do we need to manually configure this every single time?

The Solution: Laravel uses a "convention over configuration" approach. This is a fancy way of saying Laravel makes some smart assumptions to save you time. If you follow its naming conventions, things will just work automatically.

Here are the two golden rules:

  • Model Naming: The model name should be singular, with the first letter capitalized (PascalCase). For example, User, Post, Product.
  • Table Naming: The corresponding database table name should be plural, in lowercase, with words separated by underscores (snake_case). For example, users, posts, products.

If you have a Product model, Eloquent will automatically assume it corresponds to a products table. What about a BlogPost model? Eloquent is smart enough to look for a blog_posts table. It's like magic, but without the rabbits and top hats. 🎩

Creating Your First Model

Let's create a model for a blog post. Open your terminal in the root of your Laravel project and run this Artisan command:

bash
php artisan make:model Post

And... that's it! Laravel will create a new file for you at app/Models/Post.php. It will look something like this:

php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
}

This simple class is now your gateway to the posts table in your database. You didn't have to write a single line of configuration to link them. Thanks, conventions!


2. The CRUD Operations: Create, Read, Update, Delete CRUDdy Fun! 🛠️

CRUD stands for the four basic functions of persistent storage: Create, Read, Update, and Delete. These are the bread and butter of almost any web application.

Let's assume we have a posts table with title and content columns.

Create: Making New Things

Let's create a new blog post and save it to the database.

php
use App\Models\Post;

// Create a new Post instance
$post = new Post;

// Set its properties
$post->title = 'My Awesome First Post';
$post->content = 'This is the beginning of a beautiful blog.';

// Save it to the database
$post->save();

When you call the save() method, Eloquent generates an INSERT SQL query behind the scenes, fills in the values, and executes it. You just dealt with an object, and Eloquent handled the database chatter.

Read: Finding Your Data

Now that we have a post, how do we get it back? Eloquent provides several helpful methods.

Get all posts:

php
// This will return a Collection of all Post objects
$posts = Post::all();

foreach ($posts as $post) {
    echo $post->title;
}

Find a post by its primary key (ID):

php
// Find the post with an ID of 1
$post = Post::find(1);

// Now you can access its properties
echo $post->title; // "My Awesome First Post"

Find a post with more complex queries:

What if you want to find a post with a specific title?

php
$post = Post::where('title', 'My Awesome First Post')->first();

This is much cleaner than writing SELECT * FROM posts WHERE title = 'My Awesome First Post' LIMIT 1.

Update: Changing Existing Things

Let's say you made a typo in your post title. Fixing it is easy.

php
// First, find the post you want to update
$post = Post::find(1);

// Change the property
$post->title = 'My Updated & Even More Awesome Post';

// Save the changes back to the database
$post->save();

Eloquent is smart enough to know that since this model was retrieved from the database, the save() method should generate an UPDATE query instead of an INSERT one.

Delete: Getting Rid of Things

Sometimes, a post just has to go.

php
// Find the post you want to delete
$post = Post::find(1);

// Delete it
$post->delete();

And poof! It's gone. Eloquent runs the DELETE query for you. You can also destroy records by their primary key directly:

php
Post::destroy(1);

3. Security First: Mass Assignment and Fillable Properties 🛡️

The Problem: Imagine you have a user registration form. A user submits their name, email, and password. You might be tempted to write code like this to create the user:

php
// WARNING: Potentially insecure code!
$user = User::create(request()->all());

This one line takes all the data from the incoming request and uses it to create a new user. It's convenient, but what if a malicious user added an extra field to their request, like is_admin and set it to 1? If your users table has an is_admin column, your code would happily make them an administrator without you ever intending it. This is called a Mass Assignment Vulnerability.

The Solution: Laravel protects you from this by default. If you try the code above, Laravel will throw an exception. To enable mass assignment safely, you need to explicitly tell the model which attributes are "fillable".

You do this by adding a special $fillable property to your model.

In your app/Models/Post.php model, add the following property:

php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['title', 'content'];
}

By adding title and content to the $fillable array, you are telling Laravel, "It's okay to fill these columns through mass assignment. Any other columns should be ignored."

Now, you can safely use the create method:

php
$post = Post::create([
    'title' => 'A Safe and Secure Post',
    'content' => 'This was created with mass assignment!'
]);

If a user tries to sneak in an extra field, Laravel will simply ignore it, keeping your database safe. Always, always, always define the $fillable (or its opposite, $guarded) property on your models. It's a fundamental security practice in Laravel development.


4. Basic Query Builder vs. Eloquent Methods 🤔

Laravel actually gives you two ways to talk to your database: the Query Builder and Eloquent.

  • Eloquent: As we've seen, this is the object-oriented way. You work with models and their relationships. It's expressive, readable, and elegant.
  • Query Builder: This is a more direct, fluent interface for building and running SQL queries. It doesn't use models, but works directly with tables.

Let's see the difference with an example. Let's get the titles of all posts created in the last day.

Eloquent:

php
use App\Models\Post;

$posts = Post::where('created_at', '>=', now()->subDay())->get();

This returns a Collection of Post model instances. You can then loop through them and access properties like $post->title.

Query Builder:

php
use Illuminate\Support\Facades\DB;

$posts = DB::table('posts')->where('created_at', '>=', now()->subDay())->get();

This also returns a Collection, but it's a collection of standard PHP objects, not Post model instances.

When to Use Which?

  • Use Eloquent 95% of the time. It's cleaner, more readable, and allows you to use powerful features like relationships (which we'll cover later). It's the "Laravel way".
  • Use the Query Builder for complex queries that might be difficult to express with Eloquent, or for situations where you need maximum performance and don't need the overhead of hydrating full Eloquent models (e.g., complex reports or bulk updates).

For now, stick with Eloquent. It's your new best friend for database interactions.


Further Reading 📚

To dive deeper into the world of Eloquent, the official Laravel documentation is the absolute best place to go. It's comprehensive and full of examples.

Challenge

Task

You are working on an e-commerce application and need to create an Eloquent model to interact with the products database table. The table has the following columns: id, name, price, stock, and is_active.

Your task is to write the necessary PHP code to perform the following actions:

  1. Define the Model: Create a Product Eloquent model class. Ensure it's correctly configured to interact with the products table.
  2. Secure Mass Assignment: Configure the model to only allow the name, price, and stock attributes to be mass-assigned. The is_active attribute should be guarded.
  3. Perform CRUD Operations: Write the specific Eloquent queries to:
    • Create a new product with the name 'Gaming Keyboard', price 99.99, and stock 250 using a single mass-assignment operation.
    • Find the product with an id of 42, update its price to 89.99, and persist the change to the database.
    • Delete the product with an id of 15 from the database using its primary key.

Expected result

Your final code should contain:

  1. A PHP class named Product that extends the Eloquent Model class.
  2. Inside the Product class, a protected property named $fillable initialized with an array containing the strings 'name', 'price', and 'stock'.
  3. A line of code that calls the static create() method on the Product model, passing an associative array with the specified product details.
  4. Code that first calls the static find() method on the Product model with the argument 42, assigns the result to a variable, updates the price property on that variable, and finally calls the save() method on it.
  5. A single line of code that calls the static destroy() method on the Product model with the argument 15.
php

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.