When it comes to throwing an HTTP exception when a condition is not passed, the best way is to use the abort_if()
method.
abort_if()
method?The abort_if()
method is a method that renders an exception handler if the condition you passed fails.
abort_if(! Auth::user(), 403);
This method receives four parameters:
abort_if(! Auth::user()->isAdmin(), 403);
From the example above, we throw a 403 HTTP exception if the user is not an admin. This code can be used inside any function of your intended controller.
You can also add the option arguments like “message” and “headers”.
If the evaluated condition passes, the code will just flow to the next line. Otherwise, an error page like the following would show: