【问题标题】:Customize error with JSON response from controller in Laravel使用 Laravel 中控制器的 JSON 响应自定义错误
【发布时间】:2019-12-14 15:41:07
【问题描述】:

我正在使用 Jquery 3 和 Laravel 5.8,并希望使用来自我的控制器的 JSON 响应自定义错误。

我尝试从控制器返回响应,但它显示为默认错误消息。

public function destroy($id)
    {
        $po = Po::findOrFail($id);
        $po->delete();

        if($po) {
            return response()->json([
                'message' => 'Product Owner Deleted',
                'data' => $po
            ]);
        } else {
            return response()->json([
                'msg' => 'Failed to delete a product owner / Po is assigned to project'
            ]);
        }
    }

jQuery

// Delete Data
    $('body').on('click', '#btn-destroy', function(event) {
        event.preventDefault();

        let me = $(this),
            url = me.attr('href'),
            csrf_token = $('meta[name=csrf-token]').attr('content');

        Swal.fire({
            title: 'Are you sure want to delete?',
            text: "Choose Option Wisely",
            type: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, Delete it!'
          }).then((result) => {
            if (result.value) {
                $.ajax({
                    url: url,
                    method: 'POST',
                    data : {
                        '_token': csrf_token,
                        '_method': 'DELETE'
                    },
                    beforeSend: function () {
                        toastr.warning('Deleting Data...', 'WARNING');
                    },
                    success: function(data) {   
                        toastr.success(data.message, 'SUCCESS');
                        $('#datatable').DataTable().ajax.reload();
                    },
                    error: function(xhr) {
                        let error = xhr.responseJSON; 
                        toastr.error(error.msg, 'ERROR');
                    }
                });
            }
        });
    });

我想在条件下返回错误,如果为真则显示此,如果为假则显示此。但是,它总是返回如下错误:

" SQLSTATE[23000]:违反完整性约束:1…(id)) (SQL: delete fromposwhereid` = 1"

【问题讨论】:

  • 你的桌子和模型怎么样?我会更具体地使用 where $po = Po::where('id', $id)->first(); 选择记录
  • @Skeldar Model (pasted.co/7f15e4a1] Migration pasted.co/a654641c 但是......当我使用 first() 时它仍然相同。
  • @HudaPrasetyo 您的表是否与其他具有主键/外键的表相关?

标签: jquery laravel


【解决方案1】:

这样改变你的状况。

   $po = Po::findOrFail($id);

    if($po->delete()) {
        ...
    } else {
       ...
    }

【讨论】:

  • 嗯.. 还是一样的结果。它返回默认错误消息
  • 请试试这个查询生成器,比如DB::table('pos')->where('id', $id)->delete();
  • truncate 表并使用implicit 模型绑定进行删除并检查ajax 请求success 函数中的状态..
  • 等等...你能解释得更具体一些吗?,我没明白。 :D
【解决方案2】:
public function addCourse(Request $request)
 {
   $courseData = new Course();
   $courseSaved = $courseData->save();
   if ($courseSaved) {
     return response()->json(
       [
        'status' => 1,
        'message' => 'Course added successfully.'
       ]
     );
    } else {
       return response()->json(
          [
           'status' => 0,
           'message' => 'Something Was Wrong.'
          ]
        );
   }
 }
}

【讨论】:

  • 请在您的答案中插入 cmets,以便所有人都清楚。谢谢。
猜你喜欢
  • 2016-08-30
  • 2019-04-03
  • 1970-01-01
  • 2018-03-14
  • 2020-03-13
  • 1970-01-01
  • 1970-01-01
  • 2018-06-11
  • 2016-07-04
相关资源
最近更新 更多