0

I'm having trouble getting this thing to work. Basically this function is called once I click the delete button of an user config. Users can have multiple configs. What happens is that once I delete a config it looks for another one, if found it sets that as the current profile. If not it should set the config_done back to 0. the first bit works fine but if $firstProfile returns nothing, instead of entering the else it returns me an error..

code:

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

error:

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

Keep in mind that I'm very new to Laravel and the whole MVC environment.

J.Koppen
  • 121
  • 2
  • 4
  • 14
  • Eloquent will return null if no results are found you can wrap `User::find` result in `if` statement. And if it's Collection you can check using any of http://stackoverflow.com/questions/20563166/eloquent-collection-counting-and-detect-empty – arma Sep 25 '16 at 16:45
  • I tried following their examples by wrapping `$firstProfile` in an `if` statement but it returns an error: `Trying to get property of non-object` – J.Koppen Sep 25 '16 at 16:59

1 Answers1

2

Eloquent will return null if no result is found. You're dealing with objects here, so rather than checking the count, you can just do this.

$firstProfile = UserConfig::where('user_id', $uid)->first();

if($firstProfile){
    // success
} else {
    // not result
}

The $firstProfile variable will either be an instance of UserConfig or it will be null, no need to check the count.

ollieread
  • 6,018
  • 1
  • 20
  • 36
  • Thanks, i tried this before without success. Then i noted you took `->id` out after `first()` So i did the same and that fixed the problem! Thanks again. – J.Koppen Sep 25 '16 at 18:10