Adam Hopkinson
Adam Hopkinson

Reputation: 28795

Amending foreign key on a Laravel relationship

In Laravel (v5.7.12), I have two models - User and Project.

A user has an id and can have many projects. A project has an owner_id.

I can't seem to configure the relationship correctly. In my user model, I have:

/**
 * Get the projects associated with the user.
 */
public function projects()
{
    $this->hasMany('\App\Project', 'owner_id', 'id');
}

In my project model, I have:

/**
 * Get the owner associated with the user.
 */
public function owner()
{
    $this->belongsTo('\App\User', 'id', 'owner_id');
}

But calling either $user->projects() or $project->owner() returns null.

How should I configure my non-standard relationship keys?

Upvotes: 1

Views: 35

Answers (1)

Mahdi Jedari
Mahdi Jedari

Reputation: 758

You forgot to return the method:

public function projects()
{
    return $this->hasMany('\App\Project', 'owner_id');
}

Do this also for the second one:

public function owner()
{
    return $this->belongsTo('\App\User', 'owner_id');
}

Upvotes: 3

Related Questions