Eloquent Basics — Laravel

Eloquent is Laravel's way to read and write database tables through PHP objects, without writing SQL yourself. A model is a class in app/Models that manages…

Fetching one book in plain PHP takes four steps: build the string "SELECT * FROM books WHERE id = " . $id, send it with mysqli_query, take the row with mysqli_fetch_assoc, then read $row['title']. If you forget to make $id safe just once, what a visitor types can change the shape of that query (an SQL command to the database). That is SQL injection.

Eloquent does all of those steps for you. It's Laravel's built-in ORM: a way to read and write database tables through PHP objects, without writing SQL yourself. Each table has one model, a class in the app/Models folder. The Book model manages the books table, and each row in that table becomes one Book object.

Picture the librarian at the library's front desk. You only ask "bring me book number 1" or "record this new book". The librarian goes into the storeroom and fills in the catalogue card. In Laravel, the librarian is Eloquent, the storeroom is the database, and each catalogue card is one row of a table. You write Book::find(1), then Eloquent builds the SQL, sends it to the database, and hands the result back as an object.

Model: one class for one table

The books table was created in the Migrations lesson. Now make its model with Artisan:

php artisan make:model Book

The terminal answers:

   INFO  Model [/home/budi/library/app/Models/Book.php] created successfully.

The new file holds a Book class that is still empty. This is the file after you add the $fillable line:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    protected $fillable = ['title', 'author', 'stock', 'isbn'];
}

In the Lab and in the examples below, the books table holds three books:

id title author stock
1 The Rainbow Troops Andrea Hirata 3
2 This Earth of Mankind Pramoedya Ananta Toer 0
3 Beauty Is a Wound Eka Kurniawan 2

Reading: all() and find()

This is how you read books from that table. The // comment on each line shows the SQL Eloquent sends, or what that line prints:

use App\Models\Book;

$books = Book::all();     // select * from "books"
echo count($books);       // 3

$book = Book::find(1);    // select * from "books" where "books"."id" = 1 limit 1
echo $book->title;        // The Rainbow Troops
echo $book->stock;        // 3

$missing = Book::find(9); // select * from "books" where "books"."id" = 9 limit 1
var_dump($missing);       // NULL

Saving: create()

This is how you save a new book:

$book = Book::create([
    'title' => 'The Dancer',
    'author' => 'Ahmad Tohari',
    'stock' => 1,
]);

echo "New book: " . $book->title; // New book: The Dancer
echo $book->id;                   // 4

This is the SQL Laravel sends for that create():

insert into "books" ("title", "author", "stock", "updated_at", "created_at") values ('The Dancer', 'Ahmad Tohari', 1, '2026-10-09 09:30:00', '2026-10-09 09:30:00')

Changing and deleting

This is how you change the stock of one book, then delete two books. The comments under update() and delete() show the SQL that is sent:

$book = Book::find(1);
$book->update(['stock' => 2]); // one copy of The Rainbow Troops is borrowed
// update "books" set "stock" = 2, "updated_at" = '2026-10-09 09:31:00' where "id" = 1

$book = Book::find(3);
$book->delete();
// delete from "books" where "id" = 3

Book::destroy(2); // delete straight by id, without a find() first

BookController uses Eloquent

In the Controller lesson, BookController kept the books in a $books array. Now the books come from the table, so that array isn't needed any more:

use App\Models\Book;

class BookController extends Controller
{
    public function index()
    {
        return response()->json(Book::all());
    }

    public function show(string $id)
    {
        return response()->json(Book::findOrFail($id));
    }
}

The usual Laravel way is shorter still. It is called route model binding. Change {id} in the route to {book}, then ask for a Book object right in the method's parameter:

// routes/web.php
Route::get('/books/{book}', [BookController::class, 'show'])->name('books.show');

// app/Http/Controllers/BookController.php
public function show(Book $book)
{
    return response()->json($book);
}

$fillable and mass assignment

Mass assignment means filling many columns at once from one array, like create([...]) and update([...]). The danger is in code such as Book::create($request->all()), because $request->all() holds every field that was sent. A visitor can add their own field to the form, say is_admin, and so fill a column they should never be able to fill. $fillable is the allow list:

Model Book::create([...])
no $fillable MassAssignmentException: Add [title] to fillable property to allow mass assignment on [App\Models\Book]. No query is sent.
with $fillable saved. Keys not on the list, such as is_admin, are silently dropped.

To turn a key like is_admin into an error instead of silently dropping it, call Model::preventSilentlyDiscardingAttributes() in the boot() method of AppServiceProvider (a class in app/Providers for your app's settings).

Laravel 13 also accepts the same list as an attribute (a PHP note written with #[...]) above the class: #[Fillable(['title', 'author'])]. In the exercise, you use $fillable.

⚠️ Saves that fail, reads that come back null

TL;DR: Eloquent is Laravel's way to read and write database tables through PHP objects, without writing SQL yourself. A model is a class in app/Models that manages one table (Book for books), made with php artisan make:model Book. Book::all() returns a Collection (a kind of array of Book objects) of every row. Book::find(1) returns one object, or null when that id doesn't exist. Book::findOrFail(1) answers 404 when that id doesn't exist. Book::create([...]) sends one INSERT, fills created_at and updated_at, and returns the object with its new id. update([...]) sends only the changed columns, and delete() removes the row. create() and update() only fill columns listed in $fillable (the list of columns that may be filled from an array). With no $fillable at all, Laravel throws MassAssignmentException.

⚡ One model for one table

Write:

class Book extends Model
{
    protected $fillable = ['title', 'author', 'stock', 'isbn'];
}

Meaning: Eloquent is Laravel's way to read and write database tables through PHP objects. The Book model (a class in app/Models) manages the books table, and each row of that table becomes one Book object. $fillable is the list of columns that may be filled from an array.

⚡ Reading: all() and find()

Write:

$books = Book::all();  // every row, a Collection
$book = Book::find(1); // one Book object
echo $book->title;     // The Rainbow Troops
Guess first: Book::find(9), but there's no book with id 9. What do you get?

null. Not an error, not an empty Book object. To answer with a 404 instead, use Book::findOrFail(9).

Meaning: all() fetches every row as a Collection (a kind of array of Book objects). find() looks up one row by its id. Columns are read like properties: $book->title.

⚡ Saving: create()

Write:

$book = Book::create([
    'title' => 'The Dancer',
    'author' => 'Ahmad Tohari',
    'stock' => 1,
]);

echo "New book: " . $book->title;

Meaning: create() saves one new row with one INSERT. Eloquent fills created_at and updated_at, then returns the object with its new id. Columns not in $fillable aren't filled.

In the exercise, print the product names from the objects that create() and find() return. Don't type the names again.

What you will learn