killstreet killstreet - 7 months ago 14
PHP Question

Laravel custom errors with model injected into controller

So I was coming across a problem which I haven't exactly been able to resolve and having no idea where I should start with this.

I know Laravel has a nice

function but I seem to be unable to use that in my case. So for example I have a route as follow:

Route::get('user/{user}', 'UserController@show);

My controller

public function show(User $user)
//never reaches this section

Now this would normally work, but if the record does not exists Laravel throws the error before I get inside the function. Is there a nice and easy way of catching the error without changing my function to

public function show($id)
$user = User::findOrFail($id)

I find it much nicer to have the user class in my function parameter and wish not to remove it there.


Per the Laravel Docs for Route Model Binding (scroll down to the 'Customizing The "Not Found" Behavior' heading):

If you wish to specify your own "not found" behavior, pass a Closure as the third argument to the model method:

$router->model('user', 'App\User', function () {
    throw new NotFoundHttpException;

Earlier they specify where to place that code:

You should define your model bindings in the RouteServiceProvider::boot method.