Tuesday, May 23, 2017

hasManyThrough with multiple simple Pivot tables in play using Laravel Eloquent

  • User can have multiple profiles.
  • Each profile will have multiple Projects.
  • Projects will have multiple Tasks.

I want to show all the tasks assigned to user across all projects and profiles in a single view:

public function tasks()
{
    $result = collect();
    $profiles = $this->belongsToMany(\App\Profile::class);
    //now go thru each profile and find all the projects, then tasks
    $profiles->each(function($profile) use (&$result){
         $projects = $profile->projects()->get();
         $projects->each(function($project) use (&$result){
            $tasks = $project->tasks()->get();
            $tasks->each(function($task) use (&$result) {
                $result->push($task);}
          });
    });        
    return $result;
}

This does work but it feels really hobbled together. With multiple pivot tables in play is there a more efficient way to do this with Eloquent/Laravel?



via abbur

Advertisement