【问题标题】:Laravel - trying to Delete the Old records before insert New recordsLaravel - 在插入新记录之前尝试删除旧记录
【发布时间】:2021-04-13 21:21:06
【问题描述】:

我正在尝试在使用 Laravel 插入新记录之前删除旧记录。

首先我尝试使用 delete() ,然后发现 404 not found 错误,因为我使用的是控制器。

更改为destroy(),现在我面临BadMethodCallException 错误

BadMethodCallException
调用未定义的方法 Illuminate\Database\Eloquent\Builder::destroy()

我的代码:

MyClass::where('field_id', $id)->destroy();

我被卡住了,不知道如何正确地做到这一点。它的想法是删除旧记录并在其后插入新记录。

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    为避免 404 错误,您可以尝试以下操作:

    public function destroy($id)
    {
        $data = Model::where('id', $id)->firstOrFail();
        
        $data->delete();
        
        return redirect()->back()->with('success', 'Record has been deleted permanently..!');
    }
    

    【讨论】:

      【解决方案2】:

      尝试将您的控制器方法设置为这样的:

      /**
       * Remove the specified resource from storage.
       *
       * @param  int  $id
       * @return \Illuminate\Http\Response
       */
      public function destroy($id)
      {
          MyClass::where('field_id', $id)->delete();
      
          return response()->json(['success' => true]);
      }
      

      【讨论】:

      • 在控制器中包含此命令并得到相同的“404 not found”错误。
      • 尝试从php artisan tinker运行一个测试命令,你也可以分享你的路由文件的相关部分吗?
      【解决方案3】:

      如果你想避免 404 错误,你可以这样做:

      public function delete($id)
      {
          $data = MyModel::where('field', $id)->get();
      
          if(count($data)){ 
      
            $data->delete();
      
          }
      
          return response()->json(['success' => true]);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-09
        • 1970-01-01
        • 2016-12-29
        • 2015-02-02
        • 1970-01-01
        • 2012-03-06
        相关资源
        最近更新 更多