I'm developing a REST API in Laravel. I'm using route model binding to update an item. I want to return a JSON not found response when the id is not found in the database.
This is the entry in the route api.php file:
Route::get('product/{product}', 'ProductController@show')->name('products.show');
The controller update function looks as follows:
public function update(Request $request, Product $product)
{
$request->validate([
'user_id' => 'required',
'name' => 'nullable',
'description' => 'nullable',
'price' => 'nullable'
]);
// check if currently authenticated user is the owner of the listing
if (auth::user()->id !== $product->user_id) {
return response()->json(['error' => 'You can only edit your own products.'], 403);
}
$product->update($request->only(['name', 'description', 'price']));
return new ProductResource($product);
}
With this code, Laravel automatically returns a 404 Not found view but I would like it to be a JSON response instead.
Any elegant solution to accomplish this?
You can try to modify app/Exceptions/Handler.php file with something like that:
// add this before the class declaration
use Illuminate\Database\Eloquent\ModelNotFoundException;
//....
// modify the render() function as follows
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException && $request->wantsJson()) {
return response()->json(['message' => 'Not Found'], 404);
}
return parent::render($request, $exception);
}
Let me know if it works I didn't have the time to try the code.
In the recent Laravel version (9) you can solve this by putting the below code inside the register function in app/Exceptions/Handler.php
$this->renderable(function (NotFoundHttpException $exception) {
return response()->json([
'status' => false,
'message' => 'Your message here',
], 404);
});
Ensure to import the namespace of NotFoundHttpException. If your own error is ModelNotFoundException then do it this way
$this->renderable(function (ModelNotFoundException $exception) {
return response()->json([
'status' => false,
'message' => 'Your message here',
], 404);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With