Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 67 ยท Eloquent ORM

Eloquent Models and CRUD

Learn Eloquent, Laravel's ORM: create models, follow table naming conventions, create, read, update and delete records, mass assignment with fillable, and upserts.

With the query builder you work with tables and rows. Eloquent lets you work with objects instead. Each database table gets a model, a PHP class such as Post, and each row becomes an instance of it. You write $post->title = 'Hello'; $post->save(); and Eloquent produces the UPDATE statement. This is the active record pattern: the object knows how to save and delete itself. The general idea, and its trade-offs against other ORM designs, is explained in ORM concepts.

In this lesson you will generate a model, learn the naming conventions that make configuration unnecessary, run the four CRUD operations, understand mass assignment and the fillable list, and use helpers such as firstOrCreate and upsert. It builds on migrations, which create the tables, and seeders and factories, which fill them.

Creating a model

Terminal
php artisan make:model Post
php artisan make:model Post --migration --factory --seed --controller
php artisan make:model Post -mfsc    # the same, with short flags

The generator writes app/Models/Post.php:

PHP
<?php

namespace App\Models;

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

class Post extends Model
{
    use HasFactory;

    protected $fillable = ['title', 'slug', 'body', 'published_at'];
}

The class has no columns listed. Eloquent reads attributes straight from the row, so adding a column in a migration is all it takes to see $post->subtitle.

Conventions you get for free

Eloquent guesses everything from the class name, and you override only when your database disagrees:

Setting Default for Post How to override
Table posts (snake case, plural) protected $table = 'blog_posts';
Primary key id protected $primaryKey = 'post_id';
Key type auto-incrementing integer $incrementing = false; / $keyType = 'string';
Timestamps created_at, updated_at maintained for you public $timestamps = false;
Connection the default connection protected $connection = 'reporting';

UserProfile becomes user_profiles. Following the conventions keeps models short and lets every Laravel developer read your code at once. The next stand-in shows what this convention-driven behavior looks like in plain PHP: table-name guessing, a fillable filter and dirty tracking, with no database yet.

PHP Conventions, fillable and dirty tracking

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Reading records

PHP
use App\Models\Post;

$all = Post::all();                                  // every row (careful with big tables)
$post = Post::find(1);                               // by primary key, or null
$post = Post::findOrFail(1);                         // throws ModelNotFoundException (a 404 in a route)
$first = Post::where('published', true)->first();
$latest = Post::where('views', '>', 100)->orderByDesc('created_at')->take(5)->get();
$total = Post::count();

Every query-builder method from the previous lesson works on the model class, because Eloquent forwards the call. The difference is the result: you get Post objects in a collection, not plain stdClass rows. findOrFail and firstOrFail are what you want in controllers: when the record is missing, Laravel turns the exception into a 404 response by itself. Query-building in depth continues in querying with Eloquent.

Creating records

There are two ways. Set the attributes and save:

PHP
$post = new Post();
$post->title = 'Hello';
$post->body = 'My first post';
$post->save();            // INSERT; $post->id is now set

Or pass an array to create, which builds the model and saves it in one go:

PHP
$post = Post::create([
    'title' => 'Hello',
    'body' => 'My first post',
]);

create uses mass assignment, so the attributes must be allowed, as explained below. Both ways fill created_at and updated_at for you.

Updating records

Load the model, change it, save it. Eloquent only writes the attributes that actually changed (the "dirty" ones), and does nothing at all when nothing changed:

PHP
$post = Post::findOrFail(1);
$post->title = 'A better title';
$post->save();                       // UPDATE posts SET title = ?, updated_at = ? WHERE id = ?

$post->update(['title' => 'Another']);   // fill + save in one call, also mass assignment

Useful helpers around changes: $post->isDirty() (unsaved changes?), $post->wasChanged('title') (did the last save change it?), $post->refresh() (reload from the database) and $post->touch() (bump updated_at only).

You can also update many rows with one statement:

PHP
Post::where('published', false)->update(['archived' => true]);

This runs a single UPDATE and does not load models, so model events and mutators do not fire. Because it bypasses models, fillable is not checked either, so only pass trusted data.

Deleting records

PHP
$post = Post::findOrFail(1);
$post->delete();

Post::destroy(2);               // by key
Post::destroy([3, 4, 5]);       // several keys
Post::where('views', 0)->delete();  // one DELETE, no models loaded

If the model uses soft deletes, delete() only sets a deleted_at timestamp; see model events and soft deletes.

Mass assignment and fillable

Imagine a registration form handled with User::create($request->all()). A malicious visitor adds an extra field, is_admin=1, to the POST. If the model accepted every key, they would create an administrator. Eloquent blocks this: only attributes you whitelist can be mass assigned.

PHP
protected $fillable = ['name', 'email', 'password'];   // allow-list (recommended)
// or the opposite:
protected $guarded = ['id', 'is_admin'];               // block-list; everything else is allowed

Keys outside the list are silently ignored by default. During development you can make this loud with Model::shouldBeStrict() in a service provider, which turns discarded attributes into exceptions (along with lazy-loading violations, covered in eager loading).

Prefer $fillable, and prefer $request->validated() over $request->all(): validated data contains only the fields you declared, so two protections stack. Setting an attribute directly ($user->is_admin = true) is always allowed, because that is code you wrote, not user input. Never call Model::unguard() in application code.

firstOrCreate, updateOrCreate and upsert

"Find it, otherwise make it" comes up constantly, so Eloquent has helpers:

PHP
// Find by email; if missing, create it with the extra attributes
$user = User::firstOrCreate(
    ['email' => '[email protected]'],
    ['name' => 'Ada'],
);

// Same, but build without saving
$user = User::firstOrNew(['email' => '[email protected]']);

// Find by the first array; create or UPDATE with the second
$setting = Setting::updateOrCreate(
    ['key' => 'theme'],
    ['value' => 'dark'],
);

firstOrCreate never changes an existing row; updateOrCreate does. Both run a SELECT first and then an INSERT or UPDATE, so under heavy concurrency two requests can race: back them with a unique index (see migrations).

For many rows at once, upsert sends a single statement:

PHP
Post::upsert(
    [
        ['slug' => 'intro', 'title' => 'Introduction'],
        ['slug' => 'routing', 'title' => 'Routing'],
    ],
    ['slug'],        // columns that identify a row (needs a unique index)
    ['title'],       // columns to update when the row exists
);

upsert skips models entirely, so it does not set timestamps for you unless you include them in the rows, and it triggers no events.

flowchart LR
    C["Post::create()<br/>$post->save()"] -->|INSERT| DB[("posts table")]
    R["Post::find()<br/>Post::where()->get()"] -->|SELECT| DB
    U["$post->update()"] -->|"UPDATE dirty columns"| DB
    D["$post->delete()"] -->|DELETE| DB

Eloquent turns each model operation into one SQL statement.

The last stand-in is a small active record on a real SQLite database. It guesses the table name, honors fillable, inserts or updates only dirty columns on save(), maintains timestamps (with a fixed clock so the output is repeatable) and offers find, create, delete and firstOrCreate.

PHP A tiny active record on SQLite

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Real Eloquent adds casts, relationships, events, scopes, soft deletes and much more on top of exactly this core, which the remaining lessons of the chapter cover.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. For a model class named BlogPost, what table does Eloquent use by default?

    Eloquent converts the class name to snake case and pluralizes it, so BlogPost maps to blog_posts. Set $table to override.
  2. 2. A form posts name, email and a hidden is_admin=1. The User model has $fillable = ['name', 'email']. What does User::create($request->all()) do with is_admin?

    Attributes outside $fillable are discarded during mass assignment (and raise an exception only if you enabled strict mode). Validated data would be even safer.
  3. 3. What is the difference between firstOrCreate and updateOrCreate?

    firstOrCreate only creates when nothing matches. updateOrCreate applies the second array to a matching row, or creates it when none exists.
  4. 4. You run Post::where('views', 0)->delete(). What happens?

    Deleting through a query builder is one SQL statement. Only deleting a loaded model instance fires model events.
  5. 5. What does $post->save() do when nothing was changed since the model was loaded?

    Eloquent tracks dirty attributes and only writes those. With none dirty, no query is sent.

Summary

  • A model is a class (make:model) that represents one table; each row is an object, and Eloquent writes the SQL for you.
  • Conventions: table is the snake-case plural class name, primary key id, timestamps created_at/updated_at. Override with $table, $primaryKey, $timestamps.
  • Read with all, find, findOrFail, first and any query-builder chain; create with new + save() or create(); update with changed attributes + save() or update(); delete with delete() or destroy().
  • Only dirty attributes are written. Queries such as Post::where(...)->update() or ->delete() run one statement and skip model events.
  • Protect mass assignment with $fillable (preferred) or $guarded, and pass validated data rather than $request->all().
  • firstOrCreate, firstOrNew, updateOrCreate and upsert cover "find or make it", backed by unique indexes.

Next: Querying with Eloquent