in user class model , i have this
public function projects()
{
return $this->belongsToMany('App\Project');
}
in project class model i have this :
public function users(){
return $this->belongsToMany('App\User');
}
in my projectController i have this :
public function index()
{
$TeamLeader = array();
$posts = Project::orderby('id', 'desc')->with('users')->paginate(5);
return view('Projects.index', compact('posts'));
}
in my view i have this for each :
@foreach ($posts as $post)
<tr>
<td><input type="checkbox" class="checkthis" /></td>
<td href="{{ route('Projects.show', $post->project_id ) }}">{{ $post->project_id }}</td>
<td>{{ $post->name }}</td>
<td>{{ $post->description }}</td>
<td>{{ $post->created_at }}</td>
<td>{{ $user->name}}</td>
<td><p data-placement="top" data-toggle="tooltip" title="Show"><button class="btn btn-primary btn-xs" data-title="Edit" data-toggle="modal" data-target="#show" ><span class="glyphicon glyphicon-pencil"></span></button></p></td>
<td><p data-placement="top" data-toggle="tooltip" title="Delete"><button class="btn btn-danger btn-xs" data-title="Delete" data-toggle="modal" data-target="#delete" ><span class="glyphicon glyphicon-trash"></span></button></p></td>
</tr>
@endforeach
my problem is , in my view i can not get the users name , the realation is many-to-many but iam not getting the names of the users who are involved in the project , the database structure is as you can imagine :
Users has id , name , ......
Projects has id , name , location , user_id , .....
sorry to not mention that earlier but i have this common table also :
Schema::create('project_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('project_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('project_id')->references('id')->on('projects');
$table->timestamps();
});
Actually your tables design is not many to many, It's one to many [User has many Project] if you want to make many to many relation must make a middle table (pivot table)
take a look at this
This is helpful
Add this to your migrations
Schema::create('project_user', function(Blueprint $table)
{
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')
->on('users')->onDelete('cascade');
$table->integer('project_id')->unsigned()->nullable();
$table->foreign('project_id')->references('id')
->on('projects')->onDelete('cascade');
$table->timestamps();
});
project_user
table is derived from the alphabetical order of the related model names, and contains the user_id and project_id columns
Then remove user_id column from your projects table
Finally yo can access the name of users like
$project->users[0]->name
$project->users[0]->name