spatie/laravel-or-abort
Adds an OrAbort trait to Laravel models to abort with a chosen HTTP status when common calls fail (e.g., findOrAbort($id, 500) instead of returning null/false). Note: this package is no longer maintained.
Installation:
composer require spatie/laravel-or-abort
(Note: Despite being archived, this remains a lightweight, functional package.)
Usage in Eloquent Models: Add the trait to your model:
use Spatie\OrAbort\OrAbort;
class User extends Model
{
use OrAbort;
}
First Use Case:
Replace findOrFail() with findOrAbort() for custom HTTP status codes:
$user = User::findOrAbort($id, 404); // Returns 404 if not found
$user = User::findOrAbort($id, 422); // Returns 422 (e.g., for validation-like failures)
Dynamic Abort Codes:
Useful for domain-specific failures (e.g., 403 for unauthorized access):
$resource = Resource::where('owner_id', auth()->id())->firstOrAbort(403);
Service Layer Integration: Encapsulate logic in services to centralize abort handling:
class UserService {
public function getUserOrFail($id) {
return User::findOrAbort($id, 404);
}
}
Custom Logic with OrAbort:
Extend beyond Eloquent (e.g., API responses):
$data = Cache::get('key') ?: abort(404);
// Or with the trait:
$this->assertCacheExistsOrAbort('key', 404);
use OrAbort; directly in models/controllers.use Spatie\OrAbort\OrAbort as OrAbortTrait;
Archived Package:
abort() + optional():
$model = Model::find($id) ?: abort(404);
Method Overrides:
findOrFail(), firstOrFail(), etc. Ensure no naming conflicts in your codebase.HTTP Status Codes:
999) will throw exceptions. Validate inputs:
$status = is_int($status) && $status >= 400 && $status <= 599 ? $status : 500;
OrAbort isn’t triggering, check:
use OrAbort;).findOrAbort, not findOrAbortIf).Custom Abort Logic:
Override the trait’s abort() method for logging or analytics:
protected function abort($code) {
\Log::warning("Aborted with code: $code");
http_response_code($code);
exit;
}
Non-Eloquent Models: Add static methods to other classes:
class ApiResponse {
use OrAbort;
public static function getDataOrAbort($key, $status = 404) {
return self::getData($key) ?: self::abort($status);
}
}
How can I help you explore Laravel packages today?