【问题标题】:Laravel delete model custom returnLaravel 删除模型自定义返回
【发布时间】:2019-03-13 13:58:05
【问题描述】:

好的,我正在尝试删除一个模型,然后返回一个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!'
    ]);

当我想返回自定义响应时,我是否遗漏了什么?

编辑 这是控制器方法

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

【问题讨论】:

  • 您是否希望能够在应用程序中的多个位置删除用户,即您是否有多个可以删除用户的位置?
  • 不。目前仅来自仪表板中的用户管理。
  • 既然这样,为什么要把这种逻辑放在Model中而不是放在控制器中呢?
  • 好问题。我不知道我为什么这样做,这样对我来说看起来更好,但这是不好的做法吗?检查/验证是否应该在控制器中?
  • 是的,我绝对建议将其保留在您的控制器中。你能在你调用deleteUser()的地方显示控制器方法吗?

标签: php laravel eloquent model


【解决方案1】:

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

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

【讨论】:

  • 哦哇哦..总是最小的东西...感谢您的注意和在控制器中保留一些逻辑的提示。有一些改变要做。 :D
  • @Kaizokupuffball 没关系。很高兴我能帮上忙! :)
猜你喜欢
  • 1970-01-01
  • 2018-06-19
  • 2017-10-25
  • 1970-01-01
  • 2021-07-04
  • 2016-11-06
  • 2015-03-03
  • 1970-01-01
  • 2021-01-12
相关资源
最近更新 更多