What is the abort_if() method in Laravel?
Overview
When it comes to throwing an HTTP exception when a condition is not passed, the best way is to use the abort_if() method.
What is the abort_if() method?
The abort_if() method is a method that renders an exception handler if the condition you passed fails.
Syntax
abort_if(! Auth::user(), 403);
Parameter
This method receives four parameters:
- The condition
- The error code you want to display
- Message (optional)
- Headers (optional)
Example
abort_if(! Auth::user()->isAdmin(), 403);
Explanation
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”.
Output
If the evaluated condition passes, the code will just flow to the next line. Otherwise, an error page like the following would show: