You could use a try catch block to intercept the ModelNotFound exception in the controller.
try {
//your code
} catch(ModelNotFoundException $e){
//your code when id is not found
}
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
In one of my Laravel 5 packages, I'm building a REST API using resource controllers. Responses are returned in JSON format and I have model binding set up for the resources involved, i.e.:
Route::model('category', 'Riari\Forum\Models\Category');
Route::model('thread', 'Riari\Forum\Models\Thread');
Route::model('post', 'Riari\Forum\Models\Post');
That's where I have a fundamental issue: if the user/consumer passes an invalid ID in the URL when requesting from the API, due to the model binding, a ModelNotFoundException is thrown and Laravel's exception handler kicks in, returning a 404 view response instead of a JSON one.
I want to override that, but there doesn't seem to be a way of registering an exception handler in a service provider (at least in the context of a package, without affecting other routes). What's a good way around this?
A few options I can think of are:
Neither seem ideal. Any ideas?
(Also posted on /r/laravel)
Best approach would be ... http://laravel.com/docs/5.0/routing#route-model-binding
Route::model('category', 'Riari\Forum\Models\Category', function()
{
//whatever you do here .. implementing custom exception - returning JSON etc.
throw new NotFoundHttpException;
});
Please or to participate in this conversation.