Penny
Penny

Reputation: 164

How to use Laravel relationships to create a table?

enter image description here

as you see on the diagram : the task belong to a user and a project on the same time. the user and project can have multiple tasks.

how can i use laravel relationships to create a task?

Upvotes: 0

Views: 108

Answers (1)

Autista_z
Autista_z

Reputation: 2541

Nothing comlicated. One task belongsTo project, and also one task belongsTo user. User hasMany tasks, project hasMany tasks.

Task model:

public function user() 
{
    return $this->belongsTo(User::class);
}

public function project() 
{
    return $this->belongsTo(Project::class);
}

Project model:

public function tasks()
{
    return $this->hasMany(Task::class);
}

Then when you are creating Tasks for project you can do: $project->tasks()->create([...]);

Upvotes: 2

Related Questions