The loan history page needs each borrower's name, but the loans table only stores user_id (the id of the member who borrowed). In plain PHP the answer is a JOIN, an SQL command that combines rows from two tables: SELECT loans.*, users.name FROM loans JOIN users ON users.id = loans.user_id. Then the name is read from $row['name']. Every page that needs the borrower's name writes the same join again.
In Eloquent that link is written once, as a relation: a method on the model that connects two models. The tables of those two models are linked by a foreign key, a column that holds the id of a row in another table. In the Library app, each loan (Loan) is recorded for one member (User), through the user_id column in the loans table.
Picture the notebook of loans on the librarian's desk. Each line in that notebook holds the borrower's member number. From Budi's member card you can look up every line with Budi's number: one member has many loans. From one loan line you can look up its member card: one loan belongs to one member. In Laravel, the notebook is the loans table, each line is one Loan, the member number is user_id, and a member card is one User. The first search (from a member to all their loans) is called hasMany, and the second (from one loan to its member) is called belongsTo.
Tables and the foreign key
The loans table is made with a migration like this:
Schema::create('loans', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained();
$table->foreignId('book_id')->constrained();
$table->timestamps();
});
foreignId('user_id')makes a number column that holds a member's id.->constrained()adds a foreign key rule tousers.id: the database refuses auser_idthat isn't in theuserstable (covered in the Primary Key & Foreign Key lesson).book_idis the same, pointing at thebookstable.
This is what the two tables hold (the Lab has the same data):
| users.id | name |
|---|---|
| 1 | Budi |
| 2 | Ani |
| 3 | Citra |
| loans.id | user_id | book_id |
|---|---|---|
| 1 | 1 | 1 (The Rainbow Troops) |
| 2 | 1 | 2 (This Earth of Mankind) |
| 3 | 2 | 3 (Beauty Is a Wound) |
Budi borrowed two books, Ani one, and Citra hasn't borrowed any yet.
hasMany and belongsTo
A relation is written as a method on the model:
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class User extends Model
{
public function loans(): HasMany
{
return $this->hasMany(Loan::class);
}
}
class Loan extends Model
{
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}
hasManygoes on the one side that has many: oneUserhas manyLoans. The method name is plural,loans.belongsTogoes on the side that holds the foreign key: theloanstable hasuser_id, soLoanbelongsToUser. The method name is singular,user.- Laravel guesses the column name itself:
user_id. ForhasMany, the guess comes from the model nameUser. ForbelongsTo, it comes from the method nameuser(). Both get_idadded. If your column has another name, give it in the second argument:$this->hasMany(Loan::class, 'member_id'). hasOneis likehasMany, but the result is one model. For exampleUserhasOneProfile, when each member has exactly one profile.- The word
returnis required. A method with the return type: HasManythat forgetsreturnfails with the errorReturn value must be of type Illuminate\Database\Eloquent\Relations\HasMany, none returned.
Reading a relation
This is how you read the two relations. The comments under each echo show the two queries that are sent, one from find() and one from the relation:
$budi = User::find(1);
echo count($budi->loans); // 2
// select * from "users" where "users"."id" = 1 limit 1
// select * from "loans" where "loans"."user_id" = 1 and "loans"."user_id" is not null
$loan = Loan::find(3);
echo $loan->user->name; // Ani
// select * from "loans" where "loans"."id" = 3 limit 1
// select * from "users" where "users"."id" = 2 limit 1
| Code | Result |
|---|---|
User::find(1)->loans |
a Collection holding Loans 1 and 2 |
User::find(3)->loans |
an empty Collection (Citra) |
Loan::find(3)->user |
one User object: Ani |
- A relation is read like a property, without parentheses:
$budi->loans. The first time it's read, Laravel sends its query and keeps the result. If you read it again, no new query is sent. hasManyalways returns a Collection, empty when there's nothing.belongsToreturns one model, ornull.- With parentheses,
$budi->loans(), you get the query, not the result yet. It's for chaining more conditions:$budi->loans()->where('book_id', 1)->count(). - A relation can also save:
$budi->loans()->create(['book_id' => 3]);fills inuser_idwith 1 for you.
Lazy loading and with()
This code prints how many loans each member has:
$users = User::all();
foreach ($users as $user) {
echo $user->name . ': ' . count($user->loans) . "\n";
}
// Budi: 2
// Ani: 1
// Citra: 0
Count before you read further: for these three members, how many queries go to the database?
The answer is 4 queries. $user->loans is only fetched when it's read inside the loop, and this is called lazy loading. So there is 1 query for the members, then 1 loans query per member. With 100 members it becomes 101 queries. This pattern is called N+1: N queries for N members, plus 1 query at the start.
Now change $users = User::all(); to a version that uses with():
$users = User::with('loans')->get();
// select * from "users"
// select * from "loans" where "loans"."user_id" in (1, 2, 3)
| Members | Without with() |
With with('loans') |
|---|---|---|
| 3 | 4 queries | 2 queries |
| 100 | 101 queries | 2 queries |
with('loans')is called eager loading: every loan is fetched at once with one query.in (1, 2, 3)means the loans with auser_idof 1, 2 or 3. Then Laravel gives each member its own loans. The loop sends no more queries.- The other direction works the same:
Loan::with('user')->get()fetches the members throughwhere "users"."id" in (1, 2). Id 1 is in two loans, but it is sent only once. - The N+1 Problem & Eager Loading lesson goes further: how to measure N+1 and how to prevent it.
If you only need the number, there is an even cheaper option, withCount('loans'):
$users = User::withCount('loans')->get();
// select "users".*, (select count(*) from "loans" where "users"."id" = "loans"."user_id") as "loans_count" from "users"
foreach ($users as $user) {
echo $user->name . ': ' . $user->loans_count . "\n";
}
// Budi: 2
// Ani: 1
// Citra: 0
- Only 1 query, and no loan rows are fetched. The database does the counting, and the result goes into
loans_count. - Use
with('loans')when you also read the loans themselves, andwithCount('loans')when you only need the number.
⚠️ Empty relations, multiplying queries
- Swapping the sides.
belongsTogoes on the model whose table holds the foreign key (Loan),hasManyon the other side (User). If you swap them, Laravel looks for the wrong column, and the result comes back empty or as an error. - Forgetting
return. A relation method mustreturn $this->hasMany(...), not only call it. - Looping without
with(). The code is correct, but the number of queries grows by one for each row. If you read a relation inside a loop, addwith(). - In the exercise, the models are
UserandPost.posts()on User useshasMany(Post::class),user()on Post usesbelongsTo(User::class), and the eager loading lineUser::with('posts')->get()is already in the starter.
TL;DR: A relation is a method on the model that connects two models, for example User (a member) and Loan (a loan). hasMany(Loan::class) goes on the one side (one User has many Loans) and returns a Collection, empty when there's nothing. belongsTo(User::class) goes on the side holding the foreign key, a column that holds an id from another table (loans.user_id), and returns one model or null. Laravel guesses that column's name itself: user_id. Read without parentheses ($user->loans), you get the result. With parentheses ($user->loans()), you get the query. Reading a relation inside a loop sends one query per row (lazy loading, the N+1 pattern). User::with('loans')->get() fetches everything in 2 queries.
⚡ Two sides of one relation
Write:
class User extends Model
{
public function loans(): HasMany
{
return $this->hasMany(Loan::class);
}
}
class Loan extends Model
{
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}
Meaning: A relation is a method on the model that connects two models: User (a member) and Loan (a loan). hasMany goes on the one side: one User has many Loans. belongsTo goes on the side holding the foreign key (a column that holds an id from another table): the loans table has user_id. Laravel guesses the user_id column itself. The return is required.
In the exercise, the models are User and Post, with the same pattern.
⚡ No parentheses gives the result
Write:
echo count($budi->loans); // 2
echo $loan->user->name; // Ani
Meaning: $budi holds the member Budi (User::find(1)), and $loan holds one loan that belongs to Ani (Loan::find(3)). A relation is read like a property, without parentheses. The first time it's read, Laravel sends one query to fetch it. hasMany gives a Collection (empty when there's nothing), belongsTo gives one model or null. With parentheses, $budi->loans(), you get the query, to chain more onto it.
⚡ with() saves queries
Guess first: you loop over three members from User::all() and read $user->loans inside. How many queries go out?
Four: one for the members, then one per member. With 100 members it's 101. This pattern is called N+1: N queries for N members, plus 1 query at the start.
Meaning: User::with('loans')->get() fetches every loan at once with one query, in (1, 2, 3) (the members with id 1, 2 or 3), so 2 queries are enough however many members there are.