Im about to make Create Model Eloquent by having two table (one to one relationship) Task a parent to E-katalog as a child. But it doesn’t work for my relation id(task_id) in my Ekatalog table
this is my Tables looks like
Task
id
title
E-Katalog
id
type
task_id
My migrations :
Schema::create('tasks', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->timestamps();
}
Schema::create('ekatalogs', function (Blueprint $table) {
$table->id();
$table->foreignId('task_id')->nullable(),
$table->string('type');
->nullable();
}
Relation in Model in my Task:
public function ekatalog(){
return $this->hasOne(Ekatalog::class);
}
Controller :
//validation
$taskData = $request->validate([
'title' => 'required|max:255']);
$ekatalogData = $request->validate([
'type' => 'max:255']);
//create
$task->create($taskData);
$task->ekatalog()->create($ekatalogData);
the code is working, but task_id in my Ekatalog is null. i thought it automatically make or generate value id by itself from parent’s id(Task). How can i make it work?
>Solution :
You’re correct in thinking that Eloquent should automatically set the task_id value in the Ekatalog table when you create a new Ekatalog instance through the ekatalog(). However, it looks like you have a small syntax error in your migration that’s preventing this from working correctly.
Schema::create('ekatalogs', function (Blueprint $table) {
$table->id();
$table->foreignId('task_id')->nullable();
$table->string('type')->nullable();
$table->timestamps();
});
Note the removal of the comma after the foreignId('task_id')->nullable() line. This should allow you to properly set the task_id value in the Ekatalog table when creating a new Ekatalog instance through the ekatalog() relationship of a Task instance
$task = Task::create(['title' => 'My Task']);
$ekatalog = $task->ekatalog()->create(['type' => 'My Ekatalog Type']);
This should set the task_id value in the Ekatalog table to the ID of the new Task instance.