Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

i'm also new to laravel but i'll try to help. from my understanding you have a many to many relationship

  • projects can have many users? yes
  • users can have many projects? yes

than you have a many to many relationship.

you should try to use the models of user and projects. something like this in the user model:

   public function projects(){
       return $this->belongsToMany('Project','project_user','project_id','user_id')
   }

in the project model:

   public function users(){
        return $this->belongsToMany('User','project_user','user_id','project_id')
   }

than in your view you should be able to do something like this:

@foreach($users as $user)
    @foreach($user->projects as $project)
             {{ $project->project }}
    @endforeach
@endforeach
Last updated 2 years ago.
0

Thanks for the fast reply Alex. Unfortunately that's still not working. I have copied your structure over to my site but it is only returning the data for the users, when I try to get the project name through the $project->project property it returns nothing. I will have to investigate further. thanks for your help though

Last updated 2 years ago.
0

a stupid question: did you check to see if the user has a project associated to it in db ? does the project_user table have data in it?

it should work

Last updated 2 years ago.
0

Thanks for getting back to me Alex. Yes the pivot table has the correct projects and users associated with it. and the foreign keys on the project_user table are the primary keys on the projects and users table respectively.

I was able to get the query to somewhat work, but it doesn't return all users for each project. At the moment in testing there is only three users and two projects. all users are on the first project and only the first two are on the second. It works perfectly with my join but not through Model->belongsToMany.

Route::get('testing', function(){

	$projects = Project::all();

	foreach($projects as $project ){
		echo $project->project;

		foreach($project->users as $user){
			echo $user->name;
		}
	}
});
Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.