Laravel 5: Conditionally Throwing Exceptions With throw_if

April 14, 2018 —John Koster

The throw_if function can be used to throw an exception if the supplied $boolean value evaluates to true. The supplied $parameters will be passed along to the exception's constructor.

#Signature

The signature of the throw_if function is:

1function throw_if(
2 $boolean,
3 $exception,
4 ...$parameters
5);

#Example Use

In the following example we will use the throw_if function to throw an exception when the supplied value is 10:

1 
2function throwIfExample($value) {
3 throw_if(
4 $value == 10,
5 Exception::class,
6 'The value must not be 10!'
7 );
8 
9 // Do something with the value when it is not 10.
10}
11 
12// Will not throw an exception.
13throwIfExample(3);
14 
15// Will throw an exception.
16throwIfExample(10);

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.