Laravel throw_if() and throw_unless() Method Example

Do you know how to use throw_unless() and throw_if() in Laravel ?  We can check some condition like middleware or authorization in Laravel using throw_if() or throw_unless() method in Laravel.

The throw_if function throws the given exception if a given boolean expression evaluates to true: See the below example

throw_if(! Auth::user()->isAdmin(), AuthorizationException::class);

throw_if(
    ! Auth::user()->isAdmin(),
    AuthorizationException::class,
    'You are not allowed to access this page.'
);

 

The throw_unless function throws the given exception if a given boolean expression evaluates to false: See the given example to understand

throw_unless(Auth::user()->isAdmin(), AuthorizationException::class);

throw_unless(
    Auth::user()->isAdmin(),
    AuthorizationException::class,
    'You are not allowed to access this page.'
);

 

Hope it can help you.