使用Laravel中控制器的JSON响应来自定义错误

时间:2019-08-07 04:30:48

标签: jquery laravel

我正在使用Jquery 3和Laravel 5.8,并希望通过My Controller的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');
                    }
                });
            }
        });
    });

我想返回条件错误,如果为true则显示为,如果为false则显示为。但是,它总是返回错误,如:

“ SQLSTATE [23000]:违反完整性约束:1…{( id )) (SQL: delete from pos where id` = 1”

2 个答案:

答案 0 :(得分:0)

那样改变你的状况。

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

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

答案 1 :(得分:0)

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.'
          ]
        );
   }
 }
}