Table names are plural, as are many relations. Models are singlular, as are one relations. It helps to say it out loud.
- A task may have one category which can have many tasks: This is a one-to-many relationship between tasks and task_categories.
- A task may have many categories which can have many tasks: This is a many-to-many relationship.
Assuming that a task can only have one category, but the categories can be assigned to multiple tasks (one-to-many), here's how it should look:
Migrations
//tasks
class CreateTasksTable extends Migration
{
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
...
$table->timestamps();
});
}
public function down()
{
Schema::drop('tasks');
}
}
//task_categories
class CreateTaskCategoriesTable extends Migration
{
public function up()
{
Schema::create('task_categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
...
$table->timestamps();
});
}
public function down()
{
Schema::drop('task_categories');
}
}
//Pivot
class CreateTaskTaskCategoryTable extends Migration
{
public function up()
{
Schema::create('task_task_category', function (Blueprint $table) {
$table->integer('task_id')->unsigned();
$table->integer('task_category_id')->unsigned();
...
$table->timestamps();
$table->unique(['task_id','task_category_id']); //Primary Key is the relation and a task and category can only be related once.
$table->foreign('task_id')
->references('id')
->on('tasks');
$table->foreign('task_category_id')
->references('id')
->on('task_categories');
});
}
public function down()
{
Schema::drop('task_task_category');
}
}
Models:
class Task extends Model {
public function categories(){
return $this->hasMany( '\App\TaskCategory');
}
}
class TaskCategory extends Model {
public function task() {
return $this->belongsTo('\App\Task');
}
}
Controller:
return view('tasks.index', [ 'tasks' => Task::all() ]);
View (index.blade.php):
<ul>
@foreach( $tasks as $task)
<li>{{$task->name}}</li>
<ul>
@foreach($task->categories() as $category)
<li>{{$category->name }} </li>
@endforeach
</ul>
@endforeach
</ul>