Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

saileshbro's avatar

Relationship with three different tables

Hello, I have a model Staffs, Project, and Roles, What I wanted to do is a project has different staffs having a role. For example a project can have 10 staffs each assigned with different roles. How can we do this using eloquent?

0 likes
4 replies
saileshbro's avatar

Hello thanks for the response, I was trying something like a project has staffs with each role, for example a prolect has staff 1 which is an editor, staff 2 which is a viewer and so on.. can you help me with this, i am new to laravel relations.

piljac1's avatar
piljac1
Best Answer
Level 28

To achieve the stated requirements, your database should consist of 4 tables.

Here's the simplified version of the database

staffs

  • id
  • role_id
  • other columns

roles

  • id
  • other columns

projects

  • id
  • other columns

project_staff

  • id (optional, but useful in certain contexts)
  • project_id
  • staff_id

You need that 4th table to support the fact that a staff member can be assigned to multiple projects and that a project can have multiple staff members assigned to it.

As for model relationships :

Project

/**
 * Staff members that belong to the project.
 */
public function staffs() {
    return $this->belongsToMany('App\Staff');
}

Staff

/**
 * Projects that belong to the staff member.
 */
public function projects() {
    return $this->belongsToMany('App\Project');
}

/**
 * The role that the member belongs to.
 */
public function role() {
    return $this->belongsTo('App\Role');
}

Role

/**
 * Staff members having the current role
 */
public function staffs() {
    return $this->hasMany('App\Staff');
}
piljac1's avatar

To understand the difference between has one (or has many) and belongs to (or belongs to many), I recommend that you read this article which explains it very well, even though the code examples are not Laravel relations.

Please or to participate in this conversation.