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'];
}
class Book extends Modelis enough to connect the model to the table. Laravel guesses the table name from the model name:Bookbecomesbooks(lowercase, English plural). If your table has another name, writeprotected $table = 'catalog';.$fillableis the list of columns that may be filled from an array, for example bycreate(). The section "$fillable and mass assignment" explains what it is for.
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
Book::all()fetches every row and returns a Collection: a kind of array ofBookobjects, which you canforeachover andcount().Book::find(1)looks up a row by its primary key (id) and returns oneBookobject. Columns are read like properties:$book->title,$book->stock.Book::find(9)still sends a query, but it finds no row. The result isnull, not an error and not an emptyBookobject.Book::findOrFail(9)throws aModelNotFoundExceptionwith the messageNo query results for model [App\Models\Book] 9. Laravel answers that exception with a 404 page. UsefindOrFail()on a detail page such as/books/{id}.
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')
create()makes the object and saves it to the database right away: oneINSERT.created_atandupdated_atare filled in by Eloquent itself, because the migration hastimestamps().- The result is an object that already has its new
idfrom the database. So$book->titleand$book->idcan be read right away. Print values from that object, don't type them again.
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
update([...])fills the columns, then saves them. Another way with the same result:$book->stock = 2;then$book->save();.- Laravel only sends the columns that changed, plus
updated_at. If no column changed, noUPDATEis sent. For example,Book::find(2)->update(['stock' => 0])sends nothing: the stock of This Earth of Mankind is already 0. delete()removes that row. The id of a deleted row is never reused: the next new book gets id 5, not 3.
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 routes are exactly the same (
/booksand/books/{id}). Only the methods' bodies change. GET /books/9is answered with a 404 byfindOrFail(). So theisset(...)check you wrote yourself before isn't needed any more.- Models and Collections can go straight into
response()->json(). Laravel turns them into JSON,created_atandupdated_atincluded.
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);
}
- Laravel itself looks up the book with the id from the address.
GET /books/9is answered with a 404 beforeshow()is called. - The parameter name in the route (
{book}) must match the variable name in the method ($book). If they differ, for exampleshow(Book $item), Laravel looks nothing up.$itemis an emptyBookobject, and the answer is200with the body[].
$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
- Forgetting
$fillable.create()fails right away withMassAssignmentException. Add the column names to$fillable. - Using the result of
find()without checking. If the id doesn't exist,$bookholdsnull, and your code stops at$book->titlewith the errorAttempt to read property "title" on null. Check first, or usefindOrFail(). $book->update()on anull. You getCall to a member function update() on null. The cause is the same: the id wasn't found.- Typing the value again.
echo "New book: The Dancer";prints the same text but doesn't prove the book was saved. Read it from the object:echo "New book: " . $book->title;. In the exercise, the checker looks for this.
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.