J.Koppen J.Koppen - 1 year ago 137
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

returns nothing, instead of entering the
it returns me an error..


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;

$user = User::find($uid);
$user->current_profile = $firstProfile;

return view('/settings');
} else {
$user = User::find($uid);
$user->config_done = 0;

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

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

Answer Source

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();

    // 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download