Reputation:
I am using Route model binding using the id of a product and my route looks like this:
Route::get('product/{product}', ProductController@index');
I also have a custom ProductNotFoundException which I want to return when the route model binding only for this model fails to get the row (the row does not exist or is soft deleted.)
Any ideas how I could achieve that?
The two solutions I thought of are:
I chose to go with the second and do the following
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
*
* @return \Symfony\Component\HttpFoundation\Response
* @throws ProductNotFoundException
*/
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException && $exception->getModel() === 'App\Models\Product') {
throw new ProductNotFoundException();
}
return parent::render($request, $exception);
}
However, I am not sure whether is a good practice to throw an exception in the exception handler.
Can anyone see any other way or advice of the above solution?
Upvotes: 0
Views: 99
Reputation: 18197
Customize the binding resolution in RouteServiceProvider
:
Route::bind('product', function ($value) {
$product = Product::find($value);
if ($product === null) {
throw new ProductNotFoundException();
}
return $product;
});
Upvotes: 1