Laravel 5- Foreach循环只保存最后一条记录?

时间:2017-11-25 14:22:54

标签: php laravel-5 laravel-5.5

我想保存我的数组数据但是当我尝试使用foreach循环时,它只保存了最后的记录。

这是表单刀片(没有不必要的HTML代码);

@foreach($categories as $key=>$category)

  <input type="hidden"  name="menusettings[{{$key}}][menu_name]" value="{{$category->category_name}}">
  <input type="hidden"  name="menusettings[{{$key}}][menu_slug]" value="category/{{$category->category_slug}}" >
  <input type="checkbox" checked name="menusettings[{{$key}}][menu_status]">
  <input type="number" value="$i" name="menusettings[{{$key}}][menu_order]" >

@endforeach

和控制器; 公共职能postUpdateMenu(请求$请求){

        $menu = new Menu;

                $request = $requests->get('menusettings');

                foreach ($request as $reques) {

                    $menu_status = isset($reques['menu_status']) ? 1 : 0;

                    $menu->menu_name = $reques['menu_name'];
                    $menu->menu_slug = $reques['menu_slug'];
                    $menu->menu_status = $menu_status;
                    $menu->menu_order = $reques['menu_order'];

                    $menu->save();
                }

    return back();


}

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

首先。不推荐您编写的代码。

如果你想按照自己的方式行事: 尝试使用以下代码替换您的代码:

            $request = $requests->get('menusettings');

            foreach ($request as $reques) {
                // every time the loop executes a new instance needs to be assigned.
                $menu = new Menu;
                $menu_status = isset($reques['menu_status']) ? 1 : 0;

                $menu->menu_name = $reques['menu_name'];
                $menu->menu_slug = $reques['menu_slug'];
                $menu->menu_status = $menu_status;
                $menu->menu_order = $reques['menu_order'];

                $menu->save();
            }

            return back();

每次循环执行与数据库的连接时,建议不要使用上面显示的方法。 现在让我们考虑另一个选项(推荐,因为这更好。) 您还需要在菜单模型

中声明以下数组
protected $fillable = [ 'menu_name','menu_slug', 'menu_status','menu_order','created_at' , 'updated_at'];

控制器代码:

        $request = $requests->get('menusettings');
        $now = date('Y-m-d H:i:s'); //alternatively you may also use Carbon::now
        $menu = [];

        foreach ($request as $reques) {
            $menu_status = isset($reques['menu_status']) ? 1 : 0;

            $menu[] = [ 'menu_name' => $reques['menu_name'] , 'menu_slug' => $reques['menu_slug'] , 'menu_status' => $menu_status , 'menu_order' => $reques['menu_order'] , 'created_at' => $now , 'updated_at' => $now];
        }
        Menu::insert($menu);
        return back();