Eloquent Relationships — Laravel

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…

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();
});

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);
    }
}

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

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

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

⚠️ Empty relations, multiplying queries

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.

What you will learn