Robin Bastiaan
Robin Bastiaan

Reputation: 702

Laravel: abort_if vs throw_if

As we know from the Laravel documentation, we can use abort_if to throw an HTTP exception if a given boolean expression evaluates to true, and throw_if to throw the given exception if a given boolean expression evaluates to true.

The example usages are given as follows:

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

Since for the end user both methods will result in an exception, there seems to be no functional difference between them. Or does Laravel handle them differently in different configurations? In what situations would one choose to implement one over the other, or is it a matter of personal taste?

Upvotes: 1

Views: 2162

Answers (1)

patricus
patricus

Reputation: 62238

The abort_if function can only throw an HttpResponseException, NotFoundHttpException, or HttpException exception, all of which are http response related. You will most typically see this used in the controller or a middleware, as these are most responsible for the http response.

The throw_if function allows you to specify the specific exception you'd like to throw, and isn't constrained to only http related exceptions. You will see this more in your application/business logic.

Upvotes: 2

Related Questions