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');
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With