I am trying to make a task management system. Users can create a task and assign multiple users to the task. So the task table will have a user_id for identifying the user who created the task. There is a pivot table that consists of user_id and task_id so that the assignees of the task can be mapped there.
tasks table details
Schema::create('tasks', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->text('content');
$table->Integer('views');
$table->foreignId('user_id')->constrained()->onDelete('cascade')->onUpdate('cascade');
$table->timestamps();
});
users table structure
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
pivot table task_user structure
Schema::create('task_user', function (Blueprint $table) {
$table->bigIncrements('id');
$table->foreignId('task_id')->constrained()->onDelete('cascade')->onUpdate('cascade');
$table->foreignId('user_id')->constrained()->onDelete('cascade')->onUpdate('cascade');
$table->string('status')->default('TODO');
$table->timestamps();
});
Task model has this
public function users()
{
return $this->belongsToMany('App\User');
}
User model has this
public function tasks()
{
return $this->belongsToMany('App\Task');
}
Now I have a Task Resource with data fetching from UserResource but I am only able to get the data from a pivot table.
return [
'id' => $this->id,
'title' => $this->title,
'content' => $this->content,
'views' => $this->views,
'user' => UserResource::collection($this->whenLoaded('users')),
'comments' => CommentResource::collection($this->whenLoaded('comments')),
'assingnees' => $this->whenPivotLoaded('users', function () {
return $this->users->pluck('pivot.user_id')->unique()->all();
}),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
I want the user details from the pivot table in assignees
and the user details from the tasks table in user
. But eventually, I ended up getting pivot table users in user
, and no assignees
variable is obtained in JSON response. How can I get both user data in separate variables?