Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

delyn12's avatar

Delete, UpdateorCreate in laravel

Good day all, I do like to ask if there is a proper way to write this code. I want to delete where id is not included in my request and update or create the new item which I have just added to the array request.

upon preforming this task. If no new array added. It does delete and update. but if there is new array added. it only update and create. The delete where in doesn't seems to work. Any better way to write the code?

    public function update_menu_node($request, $id)
    {
        MenuNode::whereNotIn('id', $request->node_id)->delete();
        if($request->menu && count($request->menu) > 0)
        {
            foreach($request->menu as $item => $key)
            {
                MenuNode::updateorcreate(
                    [
                        'id' => $request->node_id[$item],
                         'menu_id' => $id
                    ],
                    [
                    'parent_id' => $request->parent_id[$item] == 0 ? null : $request->parent_id[$item] ,
                    'name'  => $request->menu[$item],
                    'url' => $request->link[$item],
                    'position' => $item+1,
                    'target' => $request->target[$item],
                    'type' => $request->type[$item],
                ]);
            }
        }
    }
0 likes
4 replies
Snapey's avatar

so $request->node_id is an array?

And you want to delete all other records apart from those in the array?

Does the delete work?

This foreach($request->menu as $item => $key) is the wrong way around if you actually mean $item and $key

The normal format is soreach($request->menu as $key => $item)

But as you don't use $key, foreach($request->menu as $item)

Actually, your life would be easier if you renamed your form inputs like

name="menu[][name]"
name="menu[][link]"
name="menu[][target"]

Then you would be working with a proper associated array and not a numeric array

1 like
delyn12's avatar

@Snapey Thanks for your support. Does that means naming the form like this

name="menu[][name]"
name="menu[][link]"
name="menu[][target"]

I can call on the foreach request as

foreach ($request menu as $item)
{
$name = $request->menu[]['name'];
}

Kindly advice how I can follow up.

Snapey's avatar

not quite

foreach ($request->menu as $item)
{
    $name = $item['name'];
}

or preferably just use $item['name'] directly rather than copying it to a temporary variable

delyn12's avatar

@Snapey Thank you, I will give it a trial. And yes the delete works if no new array is added to the request. But if new array is added to the request it only update or create. WhereNotin is not deleted. I will bring the delete code down after updating maybe that will help.

Please or to participate in this conversation.