Some time we need to create items for the parent before creating the parent row creates. So you can use this formula for doing that action.
add a new column on your child table named temp_id
. After that when you are going to store that item, do like this -
public function storeChildData(Request $request){
$attribute = new ChildModel();
$attribute->temp_id = rand(1111,9999); // Add a random value to the attribute
...
...
$attribute->created_by = Auth::id();
$attribute->save();
// Store value on session as a array
$tempArray = session('attributeTempId', []);
$tempArray[] = $attribute->temp_id;
session(['tempId' => $tempArray]);
...
...
}
Then go to your parent store method and add like this -
public function storeParentData(Request $request)
$parent = new ParentModel;
...
...
$parent->created_by = Auth::id();
$parent->save();
// Add this for update parent id on child
ChildModel::whereIn('temp_id', session()->get('tempId'))->where('created_by', Auth::id())->update(['temp_id' => null, 'parent_id'=> $parent->id]);
session()->flash('tempId');
...
...
}
Top comments (0)