Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select from two tables Laravel 5

I use Laravels many to many relations. I have 2 tables projects and groups and pivot table project_group

Now I can do something like this:

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

It will return just Groups...Like this:

Design
SEO

But I need to return like this:

Design(Project2,Project3)
SEO(Porject1)

So for each loop I need to get group and all project linked to that group.

Here is my relation into Project modul:

public function groups(){
    return $this ->belongsToMany('App\Group','project_group')->withPivot('admin_id');
    }
like image 827
Vladimir Djukic Avatar asked Nov 10 '22 16:11

Vladimir Djukic


1 Answers

You can define the inverse of the relationship in your Group model.

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

And then, use it in your eloquent query.

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

You'll be able to loop through your groups and in each group get all projects.

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

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

$groups = Group::with(['projects' => function($query) {
  $query->where('adminid', Auth::user()->id)
}])->get();
like image 84
Needpoule Avatar answered Nov 14 '22 22:11

Needpoule