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?
$task->create($taskData) will create a new object instance. Try this:
//validation
$taskData = $request->validate([
'title' => 'required|max:255']);
$ekatalogData = $request->validate([
'type' => 'max:255']);
//create
$task = Task::create($taskData);
$task->ekatalog()->create($ekatalogData);