Reputation: 47
I want to delete a user but I only can if he/she has a photo if has not I got Trying to get property of non-object. I want to delete either way. My code:
public function destroy($id)
{
$user = User::findOrFail($id);
if(File::exists($user->photo->file)){
unlink(public_path().$user->photo->file);
$user->delete();
Session::flash('deleted_user','The user has been deleted');
return redirect("/admin/users");
}else{
$user->delete();
Session::flash('deleted_user','The user has been deleted');
return redirect("/admin/users");
}
}
Upvotes: 1
Views: 264
Reputation: 3257
I think you should first check if parameter exists and then use it to find image
public function destroy($id)
{
$user = User::findOrFail($id);
if(isset($user->photo->file) && File::exists($user->photo->file)){
unlink(public_path().$user->photo->file);
$user->delete();
Session::flash('deleted_user','The user has been deleted');
return redirect("/admin/users");
}else{
$user->delete();
Session::flash('deleted_user','The user has been deleted');
return redirect("/admin/users");
}
}
Upvotes: 1
Reputation: 2999
If the user has no photo, $user->photo
may be null so you will get an error when trying to access $user->photo->file
. To prevent the error, you have to check if $user->photo
is an object.
public function destroy($id)
{
$user = User::findOrFail($id);
if(is_object($user->photo) && File::exists($user->photo->file)){
unlink(public_path().$user->photo->file);
$user->delete();
Session::flash('deleted_user','The user has been deleted');
return redirect("/admin/users");
} else {
$user->delete();
Session::flash('deleted_user','The user has been deleted');
return redirect("/admin/users");
}
}
Upvotes: 3