Problem: Your API returns HTML 404 pages when resources aren't found, but you need consistent JSON responses for API clients.
Solution:
// In your controller - manual 404
public function show($id)
{
$user = User::find($id);
if (!$user) {
return response()->json([
'message' => 'User not found',
'error' => 'Resource not found',
'status' => 404
], 404);
}
return response()->json($user);
}
// Using findOrFail with custom exception handling
// In app/Exceptions/Handler.php
use Illuminate\Database\Eloquent\ModelNotFoundException;
public function render($request, Throwable $exception)
{
if ($request->expectsJson()) {
if ($exception instanceof ModelNotFoundException) {
return response()->json([
'message' => 'Record not found',
'error' => class_basename($exception->getModel()) . ' not found',
'status' => 404
], 404);
}
}
return parent::render($request, $exception);
}
// Global API 404 for all routes
// In routes/api.php
Route::fallback(function(){
return response()->json([
'message' => 'Endpoint not found',
'error' => 'The requested API endpoint does not exist',
'status' => 404
], 404);
});
Why it works: Laravel checks the Accept
header via expectsJson()
to determine if JSON should be returned. The exception handler catches ModelNotFoundException
from findOrFail()
and returns JSON. The fallback route handles undefined API endpoints.
Tip: Keep
Share this article
Add Comment
No comments yet. Be the first to comment!