bradsi
11/22/2019 - 2:01 PM

Your First Eloquent Relationship

Your First Eloquent Relationship

Setting Up the Task Model

php artisan make:model Task -m -f

In Migration

// task is not completed by default
$table->boolean('completed')->default(false);
// connect with project_id i.e. primary key
$table->unsignedInteger('project_id');

Wiring Up the Relationship

In Project, Project has many Tasks

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

Show Tasks in View

@if($project->tasks->count())
  <div>
    @foreach ($project->$tasks as $task)
      <li>{{ $task->description }}</li>
    @endforeach
@endif

Task Belongs to a Project

In Task model:

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