R
R
Romi2021-10-09 12:23:44
Laravel
Romi, 2021-10-09 12:23:44

Why does findOrFail() work so strangely?

All of a sudden I remembered findOrFail() - and it does indeed throw an exception if it doesn't find the model :) HOWEVER, look at the output:

{
    "message": "No query results for model [App\\Models\\User] 9999999",
    "exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",


and everything would be fine here, but the fact is that it takes the "message" from

Illuminate\Database\Eloquent\ModelNotFoundException


while "exception", as you can see, is different ...

And the main problem is that if I want to change the output in the Handler via renderable(), then I have to specify NotFoundHttpException as an argument, which does not have the getModel() method I need (for display in the message)

Is this some kind of developers jamb, or what?

Offhand, nothing came to mind, how can this be fixed in a "soft" way, can you advise something?

upd.: there is some kind of magic in general :) more it is called in the function itself

throw (new ModelNotFoundException)->setModel(
            get_class($this->model), $id
        );


where did NotFoundHttpException come from - that's another question :D

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jazzus, 2021-10-09
@romicohen

$this->renderable(function (NotFoundHttpException $e, $request) {
    if ($request->is('users/*')) {
        return response()->json([
            'message' => 'Юзер не найден'
        ], 404);
    }
});

I
iljaGolubev, 2021-10-12
@iljaGolubev

1. to the question "where did NotFoundHttpException come from..."
src/Illuminate/Foundation/Exceptions/Handler.php
2. if you don't want standard exceptions - don't use findOrFail
2.1 you can't without findOrFail - change the behavior of app/Exceptions/Handler.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question