Laravel 5.3 检查结果是否存在

26 浏览
0 Comments

Laravel 5.3 检查结果是否存在

我在让这个东西工作上遇到了麻烦。基本上,当我点击一个用户配置的删除按钮时,就会调用这个函数。用户可以有多个配置文件。当我删除一个配置文件时,它会寻找另一个配置文件,如果找到了,就将其设置为当前配置文件。如果没有找到,它应该将配置文件设置为0。第一部分运行得很好,但如果$firstProfile返回空值,它不会进入else,而是返回错误。

代码:

public function delete(UserConfig $config) {
    $user = Auth::user();
    $uid = $user->id;
    if ($uid == $config->user_id) {
      UserConfig::where('id', $config->id)->delete();
      $firstProfile = UserConfig::where('user_id', $uid)->first()->id;
      if(count($firstProfile)){
        $user = User::find($uid);
        $user->current_profile = $firstProfile;
        $user->save();
        return view('/settings');
      } else {
        $user = User::find($uid);
        $user->config_done = 0;
        $user->save();
        return view('/home');
      }
    }
  }

错误:

ErrorException in UserConfigController.php line 100:
Trying to get property of non-object
in UserConfigController.php line 100
at HandleExceptions->handleError('8', 'Trying to get property of non-object', '/Users/jordykoppen/git/beef-monitor/app/Http/Controllers/UserConfigController.php', '100', array('config' => object(UserConfig), 'user' => object(User), 'uid' => '1')) in UserConfigController.php line 100

请记住,我对Laravel和整个MVC环境非常陌生。

admin 更改状态以发布 2023年5月22日
0
0 Comments

Eloquent将在未发现结果时返回null。你在处理对象,所以不需要检查数量,可以直接这样做。

$firstProfile = UserConfig::where('user_id', $uid)->first();
if($firstProfile){
    // success
} else {
    // not result
}

$firstProfile变量将是UserConfig的一个实例或者null,没有必要检查数量。

0