Laravel throw_if and throw_unless Helpers

Laravel throw_if and throw_unless Helpers

Coming to Laravel 5.5 is two new helper methods named throw_if and throw_unless, and both are designed to make it easier to throw exceptions.

“Just like all the helpers, throw_if and throw_unless help facilitate clean and expressive code,” TJ Miller said, “In particular, these two helpers could often reduce a conditional block to a single line of code. That’s pretty z.”

Let’s take a look at these helpers and demonstrate how they work:

throw_if

Throw if, does exactly as it says. If the first param is a boolean and it’s “true,” then throw an exception.

Here is an example use case:

$foo = true;
throw_if($foo, new BarException('Foo is true'));
// or 
throw_if($foo, BarException::class, 'Foo is true'); 

Here is the complete function for reference:

function throw_if($boolean, $exception, $message = '')
{
    if ($boolean) {
        throw (is_string($exception) ? new $exception($message) : $exception);
    }
}

throw_unless

The reverse of throw_if is throw_unless and it performs exactly the same except it checks that the first param is false and then throws an exception:

$foo = false;
throw_unless($foo, new BarException('Foo is false'));
// or
throw_unless($foo, BarException::class, 'Foo is false');

And it’s complete signature:

function throw_unless($boolean, $exception, $message)
{
    if (! $boolean) {
        throw (is_string($exception) ? new $exception($message) : $exception);
    }
}

These two helpers will be available with the 5.5 release which is due out in July and be sure to join the weekly Laravel Newsletter, so you’ll get notified as soon as it is officially released.


Filed in: Laravel 5.5 / Helpers


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Mid / Sen. Software Engineer
Clearwater, FL
ShineOn
Full Stack or Back-End Developer
Alexandria, VA; Tallahassee, FL; Orlando, FL
Marketing for Change
Full Stack Software Engineer
Atlanta, GA or Remote
Voxie
Laravel/PHP Developer
Chicago, IL
Neon One
Software Engineer, Web Applications
Vaughan, ON, Canada
Blast Motion
Contract Services Software Engineer (Laravel | Vue | Tailwind)
Remote
Riverbed Technology
Senior Laravel Developer
Wilmington, NC
GE Software Inc.