you can create your own exception and throw it when no records are found
Dec 29, 2021
3
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.
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.