I have a table (hierarchies) and there is a column name hierarchy_id. In view file there is a dropdown like ( Hierarchy 1(value=1), Hierarchy 2(value=2), Hierarchy 3(value=3) .... ). When I submit the form it will check the selected hierarchy_id value to see if it exists in the table column or not. If it does, the hierarchy_id will rise by 1 from the existing value to the last value. Otherwise it will create new one at the last position.
My Code
public function create(Request $request)
{
$hierarchies = Hierarchy::all();
$sorting_slot = '';
for ($i=0; $i < count($hierarchies); $i++)
{
if( $hierarchies[$i]['hierarchy_id'] == $request->hierarchy_id )
{
$sorting_slot = $i;
}
}
if( $sorting_slot )
{
for ($i = $sorting_slot; $i < count($hierarchies); $i++)
{
$hierarchies[$i]->update(['hierarchy_id' => $hierarchies[$i]['hierarchy_id'] + 1]);
}
}
$hierarchies = new Hierarchy();
$hierarchies->name = $request->name;
$hierarchies->hierarchy_id = $request->hierarchy_id;
$hierarchies->save();
return redirect()->back()->with('create_hierarchy', 'Hierarchy Created Successfully.');
}