1
votes

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.

1
first add some code , whatever you have done . - Saurabh Mistry
I have updated my answer with an amazing grammatically correct requirement. - Rohan Shukla
may be you should try polimorphic relations ? user have many tasks, project has many tasks, projects have many users. it seems polymorhphic relation more compatible ? - Teoman Tıngır
Are you sure mate? I tried that with Post, Video and Comments. It's useful I guess when you need a single post and a single video to have multiple comments. - Rohan Shukla

1 Answers

1
votes

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