Frank Lucas Frank Lucas -4 years ago 142
PHP Question

PHP refactor if else

I have this if else structure and I want to refactor the else out since I want to clean up the code a bit. Only I am not sure how I can refactor the else out.

if ($validator->fails()) {
return Redirect::back()
->with('error_code', 5)
->withErrors($validator->errors())
->withInput();
} else {
// do something if validator does not fail
return Redirect::back();
}


Anyone has any idea how I can refactor the else out?

Many thanks in advance!

Answer Source

In this case you dont even need the else statement, since you have a return in your IF. If the validation fails, it will return and never arrive to the Redirect::back(); So use it like this:

if ($validator->fails()) {
   return Redirect::back()
       ->with('error_code', 5)
       ->withErrors($validator->errors())
       ->withInput();
}

return Redirect::back();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download