Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Kikismedia's avatar

need help with tasks project

am implementing a task system in my laravel school project, it will be an online school platform where students can complete task given to them by the admin and when they are done with the task the students can click on the complete button , a student can't create task , just participate

a student can have many tasks and a task can have many students here is my approach I am not sure

Schema::create('complete_task', function($table){
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->integer('task_id')->unsigned();
    $table->timestamps();

    $table->foreign('user_id')->references('id')->on('users');
    $table->foreign('task_id')->references('id')->on('tasks');
});

My Model:


Class CompleteTask extends Eloquent{

public function user(){
    return $this->hasMany('User');
}
public function task(){
    return $this->hasMany('task');
}

}

view

@foreach ($tasks as $task)
    <li class="medium-4 columns">
        <div class="canvas-medium">
            <img src="{{ $task->image }}">
        </div>
        <p class="title">{{ $task->name }}</p>
        <p class="owner">By 
            <a href="profile/{{ $task->user_id }}">{{ $task->user->firstname }} {{ $task->user->name }}</a>
            <a href="/complete/{{ $task->id }}">Complete</a>
        </p>
    </li>
@endforeach

My controller:

class TaskController extends BaseController{

    public function complete($id){
        $complete = new CompleteTask;
        $complete->user_id = Auth::id();
        $complete->task_id = $id;
        $complete->Save();

        return Redirect::to('/tasks');
    }

}
0 likes
1 reply
tykus's avatar

You are describing a many-to-many relationship; so, you need a Task model and a User model, along with pivot table task_user (by convention) with only the user_id and task_id foreign keys - though we might need a separate column to track whether the user has completed the task. There is no need for the CompleteTask Pivot model (at least for now). On the related models:

Task model
public function users()
{
    return $this->belongsToMany(User::class);
}
// User model
public function tasks()
{
    return $this->belongsToMany(Task::class);
}

You can then assign users to a Task using the belongsToMany methods:

class TaskController extends BaseController
{
    public function complete($id)
    {
		$task = Task::findOrFail($id);
        $task->users()->attach(auth()->id()); // this ID doesn't make sense...
        return Redirect::to('/tasks');
    }
}

Please or to participate in this conversation.