Search

Laravel 5: Conditionally Throwing HTTP Exceptions With abort_if

April 14, 2018 —John Koster

The abort_if helper function performs the same basic function as the abort helper function. The only difference is that the abort_if defines one extra parameter: $boolean; if the argument supplied for $boolean evaluates to true, the abort_if function will abort execution of the application.

This function allows you to perform a conditional check and a call to the abort function in one line.

#Signature

The signature of the abort_if function is:

1function abort_if(
2 $boolean,
3 $code,
4 $message = '',
5 array $headers = []
6);

#Example Use

The following example assumes that some $user object exists with the property admin. The example will check to make sure that the admin property is true. If not, the code will abort with a 401 (unauthorized access) error code.

1 
2// These two function calls are equivalent.
3abort_if(!$user->admin, 401);
4abort_if(($user->admin == false), 401);
5 
6// The previous examples are also equivalent to:
7if ($user->admin == false) {
8 abort(401);
9}

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.