I create a many-to-many relationship, where many projects can be assigned to many users. My problem is that I do not know how to display projects assigned to a given user. . Currently, all available projects are displayed. I created pivot table, where after adding the project I store the project id and user id. This is my code:
User.php
public function projects()
{
return $this->belongsToMany('App\Project')->withTimestamps();
}
Project.php
public function users()
{
return $this->belongsToMany('App\User')->withTimestamps();
}
ProjectsController.php
public function projects()
{
$projects = Project::latest()->get();
return view('pages.projects')->with('projects', $projects);
}
migrations:
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->longText('p_name')->nullable();
$table->timestamps();
});
}
public function up()
{
Schema::create('project_user', function (Blueprint $table) {
$table->unsignedInteger('project_id');
$table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade');
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}