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 findOrFail()
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 themodel
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.
First time answering a question so bear with me!
You can use a PHP try/catch block. So something like this:
try {
//Your code here
} catch (\Exception $e) {
return \Redirect::to('/users')
->with('error', 1)
->with('message', 'Error getting your record!');
}
And then in your Laravel blade you can do something like:
@if(!empty($error) && $error == 1)
<div>
<strong>Uh-Oh!</strong>
@if(!empty($message))
{!! $message !!}
@endif
</div>
@endif
To display the error. You can also redirect to some error page you want.