J.Koppen J.Koppen - 2 months ago 24
PHP Question

Laravel 5.3 Check if result exist

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.

Answer

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.