Rohan Shukla
Rohan Shukla

Reputation: 89

How can I implement multiple many-to-many relationship in Laravel 5.5?

I'm making a small laravel project to implement Eloquent Relationships, I have multiple models mainly (Project, Task, User, File, etc)

And a Project can have multiple users assigned, multiple files attached to it, and can also have multiple tasks. And a single Task can have multiple users assigned and can also have multiple files assigned, along with multiple other things. I have googled and implemented hasManyThrough, and belongsToMany relationships but I get confused a lot with relations. Any help?

Project.php

class Project extends Model
{

protected $fillable = ['name', 'user_id'];

public function users()
{
    return $this->belongsTo(User::class);
}

public function tasks()
{
    return $this->hasManyThrough(Task::class, User::class);
}
}

Task.php

public function user()
{
    return $this->belongsTo(User::class);
}

User.php

public function tasks()
{
    return $this->hasMany(Task::class);
}

public function project()
{
    return $this->belongsTo(Project::class);
}

The error I get is when I go to projects/1 I get multiple tasks attached to them but not multiple users.

Upvotes: 1

Views: 1657

Answers (1)

Erubiel
Erubiel

Reputation: 2972

Seem like you are missing pivot tables. im gonna make some assumptions based on your tables

Project, Task, User, File

A user can be on multiple projects and a project can have multiple users assigned. Its no logical to use task or file to get the project users, unless every user can access every project and do tasks and upload files..

But if there's some kind of assignation process (of a user to a project) you wold have to make a pivot table migration

Something like:

project_has_user or in laravel standards: users_projects

then you can implement belongsToMany relationships on both Project, and User Models

Task <-> User relationship is the same way... you should also create a users_tasks pivot table

Upvotes: 1

Related Questions