Choose from two Laravel 5 tables

I use Laravels for many relationships. I have 2 projects and groups tables and a project_group pivot table

Now I can do something like this:

 $groups = \App\Project::findOrFail(Auth::user() -> id)->groups()->where('adminid','=',Auth::user()->id)->get(); 

He will return only the groups ... Like this:

 Design SEO 

But I need to return like this:

 Design(Project2,Project3) SEO(Porject1) 

So, for each cycle, I need to assemble a group and the entire project associated with this group.

Here is my attitude towards the Project module:

 public function groups(){ return $this ->belongsToMany('App\Group','project_group')->withPivot('admin_id'); } 
+5
source share
1 answer

You can define feedback in the Group model.

 public function projects(){ return $this->belongsToMany('App\Project','project_group')->withPivot('admin_id'); } 

And then use it in your eloquent request.

 $groups = Group::with('projects')->get(); 

You can scroll through your groups and receive all projects in each group.

 foreach($groups as $group) { foreach($group->projects as $project){ //your project } } 

I really don't understand the use of Auth::user() -> id , but if you only want a project where the current user is the administrator, you can use the condition in function c.

 $groups = Group::with(['projects' => function($query) { $query->where('adminid', Auth::user()->id) }])->get(); 
+1
source

All Articles