How can I return json data when laravel catch exception? I'd like to return Json data when the data does not exist on database.
When laravel found the record from database, it returns correct json data.Yeah! If laravel have fail to search any record, it doesn't give json data! laravel just redireted the page which shows "Whoops, looks like something went wrong." and give soem extra information, "ModelNotFoundException".
Following code is what I tried.
public function show($id)
{
try {
$statusCode = 200;
$response = [
'todo' => []
];
$todo = Todo::findOrFail($id);
$response['todo']= [
'id' => $todo->id,
'title' => $todo->title,
'body' => $todo->body,
];
} catch(Exception $e) {
// I think laravel doesn't go through following exception
$statusCode = 404;
$response = [
"error" => "You do not have that record"
];
} finally {
return response($response, $statusCode);
}
}
catch(Illuminate\Database\Eloquent\ModelNotFoundException $e)