Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Nite's avatar
Level 1

How to best implement a "getOrFail" ?

I know for single model queries I can use firstOrFail(). What about queries for multiple models using get() ? I'd like to return an error similar to the one automatically sent by firstOrFail(), how should I implement that ? Atm I'm simply using abort(500) if the query returns an empty collection.

0 likes
3 replies
Snapey's avatar

you can create your own exception and throw it when no records are found

1 like
tykus's avatar
tykus
Best Answer
Level 104

The Eloquent Builder is macroable, so you can implement a Builder macro for getOrFail:

// AppServiceProvider
public function boot()
{
        \Illuminate\Database\Eloquent\Builder::macro('getOrFail', function () {
            return tap($this->get(), fn ($results)  => abort_unless($results->count(), 500));
        });
}

IMHO, 500 is an inappropriate status code 🤷‍♂️

As @snapey mentions, you can create your own Exception and rather than abort_unless use throw_unless, e.g. assuming you have created a ModelsNotFoundException:

Builder::macro('getOrFail', function () {
    return tap($this->get(), fn ($results)  => throw_unless($results->count(), new ModelsNotFoundException()));
});
1 like

Please or to participate in this conversation.