Laravel删除模型自定义返回

时间:2019-03-13 13:58:06

标签: php laravel eloquent model

好的,我尝试删除一个模型,然后返回一个response()->json([...])。出于某种原因,当我删除模型时,无论执行什么操作,它总是返回NULL

这是User模型中的函数,用于删除给定的用户。

/**
 * @return bool|\Illuminate\Http\JsonResponse|null
 * Delete user
 */
public function deleteUser()
{

    // If the admin deletes his own account we need to check if there is another admin. There must exists at least 1 admin
    if ($this->user_id == auth()->user()->user_id && (auth()->user->hasRole('admin'))) {
        if (User::whereHas('roles', function($query) { $query->where('id', 1); })->count() <= 1) {
            return response()->json([
                'success' => false,
                'message' => 'There must be another admin if you remove your own user.'
            ]);
        }
    }

   if (!$this->delete()) {
       return response()->json([
          'success' => false,
          'message' => 'Could not delete user!'
       ]);
   }

    return response()->json([
        'success' => true,
        'message' => 'User was deleted successfully!'
    ]);

我想返回自定义响应时是否缺少某些内容?

EDIT 这是控制器方法

public function postDelete(User $user)
{
    $user->deleteUser();
}

1 个答案:

答案 0 :(得分:2)

您只是在控制器方法中缺少return

public function postDelete(User $user)
{
    return $user->deleteUser();
}